【问题标题】:In rspec, why can't I use be_false etc in helper classes?在 rspec 中,为什么我不能在辅助类中使用 be_false 等?
【发布时间】:2011-03-21 04:37:31
【问题描述】:

当使用带有 rspec 测试的辅助类时,我看不到使用 .should be_false 成语。在帮助程序 .rb 文件中定义的函数中没问题,但是当它在类中时,找不到 be_false 符号。下面的例子——为什么这不起作用?如何在助手中使用 be_false 等?

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

结果

$ 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

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

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

【问题讨论】:

    标签: ruby rspec helper assertion


    【解决方案1】:

    be_true 这样的期望仅在it 块的上下文中可用。当您在 HelperFoo.new 上调用方法时,它不再在 it 操作的任何神奇类的上下文中执行。

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

    另外,如果你需要在外部定义 RSpec 示例,你应该使用Shared Example Groups

    【讨论】:

    • 谢谢,现在说得通了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 2013-08-12
    • 1970-01-01
    • 2010-11-29
    • 2012-05-02
    相关资源
    最近更新 更多