在rspec中,为什么我不能在辅助类中使用be_false等?

kdt*_*kdt 3 ruby rspec helper assertion

当使用带有rspec测试的助手类时,我看不到使用这个.should be_false成语.在helper .rb文件中定义的函数中没有问题,但是当它在类中时,be_false找不到符号.以下示例 - 为什么这不起作用?我如何be_false在助手中使用et al?

似乎有可能这样的断言只能在测试中起作用.我有帮助因为例如因故障而失败.网络通信问题实际上是真正的测试失败,因为我的帮助者使用的网络通信是被测系统的一部分.我应该如何让我的测试在helper类中优雅地失败?

结果

$ spec ./test.rb 
helper_foo 1
helper_foo 2
helper_foo 3
FunctionFoo 1
F

1)
NameError in 'my_test should test that helper classes can use should be_false etc'
undefined local variable or method `be_false' for #<HelperFoo:0x2b265f7adc98>
./helper.rb:13:in `FunctionFoo'
./test.rb:13:

Finished in 0.004536 seconds

1 example, 1 failure
Run Code Online (Sandbox Code Playgroud)

test.rb

require "helper.rb"

describe "my_test" do
    it "should test that helper classes can use should be_false etc" do

        (1 == 1).should be_true
        (2 == 1).should be_false

        helper_foo()

        instance = HelperFoo.new()
        instance.FunctionFoo
    end
  end
Run Code Online (Sandbox Code Playgroud)

helper.rb

def helper_foo
    puts "helper_foo 1"
    (1==2).should be_false
    puts "helper_foo 2"
    (2==2).should be_true
    puts "helper_foo 3"
end

class HelperFoo
    def FunctionFoo
        puts "FunctionFoo 1"
        (1==2).should be_false
        puts "FunctionFoo 2"
        (2==2).should be_true
        puts "FunctionFoo 3"
    end
end
Run Code Online (Sandbox Code Playgroud)

tri*_*ine 5

期望be_true仅在it块的上下文中可用.当你打开一个方法时HelperFoo.new,它不再在任何魔法类it操作的上下文中执行.

您应该阅读instance_eval以了解评估上下文是什么.

此外,如果需要在外部定义RSpec示例,则应使用共享示例组.