2010-07-26 56 views
3

當使用帶有rspec測試的輔助類時,我看不到使用.should be_false成語。在helper.rb文件中定義的函數沒關係,但是當它在一個類中時,找不到be_false符號。下面的例子 - 爲什麼不工作?我如何在助手中使用be_false等?在rspec中,爲什麼我不能在助手類中使用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 

回答

5

期望像be_true僅適用於it塊的上下文。當你在HelperFoo.new上調用方法時,它不再在it運行的任何魔法類別的環境中執行。

您應該閱讀instance_eval以瞭解評估上下文是什麼。

此外,如果您需要從外部定義RSpec示例,則應該使用Shared Example Groups

+0

謝謝,現在有道理。 – kdt 2010-08-03 10:21:19

相關問題