首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么是$?在RSpec中为零( Rails应用程序之外)

为什么是$?在RSpec中为零( Rails应用程序之外)
EN

Stack Overflow用户
提问于 2016-03-08 18:38:12
回答 1查看 182关注 0票数 0

我有一个在测试中使用$?.exitstatus的Rails应用程序,它运行得很好。

我正在尝试制作一个在测试中使用$?.exitstatus的gem,但我收到了以下消息:

代码语言:javascript
复制
NoMethodError:
   undefined method `exitstatus' for nil:NilClass

下面是我为再现问题而创建的两个示例文件:

superman.rb

代码语言:javascript
复制
class Superman
  def self.execute(command)
    `#{command}`
  ensure
    puts $?.exitstatus
  end
end

my_spec.rb

代码语言:javascript
复制
describe Superman do
  it 'should execute' do
    expect(Superman).to receive(:execute).and_return(1)
    expect($?.exitstatus).to be 0
  end 
end

为什么我可以在Rails规范中使用$? ,而不能在普通的红宝石中使用?我需要什么东西吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-08 18:48:54

$?返回要执行的最后一个子进程的Process::Status。如果没有执行子进程,您将得到nil

在这种情况下,由于您实际上没有调用Superman.execute,因此不需要返回子进程状态。此外,即使您将Superman.execute("ls")添加到您的规范中,您也在上面添加了它,并且同样的情况仍然成立。

尝试:

代码语言:javascript
复制
describe Superman do
  it 'should execute' do
    # There's really no reason for this expect(..).to receive anyway
    # since it's pretty obvious it's going to get called since we're
    # calling it directly right below.
    expect(Superman).to receive(:execute).and_call_original
    Superman.execute("ls")
    expect($?.exitstatus).to eq(0)
  end
end

产量:

代码语言:javascript
复制
rspec ./superman_spec.rb
0
.

Finished in 0.01054 seconds (files took 0.10346 seconds to load)
1 example, 0 failures
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35875338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档