3

.should be_falserspec テストでヘルパー クラスを使用する場合、イディオムの使用方法がわかりません。ヘルパー .rb ファイルで定義された関数では問題ありませんが、クラス内ではbe_falseシンボルが見つかりません。以下の例 -- なぜこれが機能しないのですか? be_falseヘルパーで et alを使用するにはどうすればよいですか?

このようなアサーションがテスト自体でのみ機能するのは、意図的なものである可能性があります。たとえば、失敗する可能性のあるヘルパーがあります。私のヘルパーが使用するネットワーク通信はテスト中のシステムの一部であるため、ネットワーク通信の問題は実際には正真正銘のテストの失敗です。ヘルパー クラス内でテストを正常に失敗させるにはどうすればよいですか?

結果

$ 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
4

1 に答える 1

5

のような期待値は、ブロックbe_trueのコンテキストでのみ使用できます。itでメソッドを呼び出すと、魔法のクラスが動作するHelperFoo.newコンテキストでは実行されなくなります。it

instance_eval評価コンテキストとは何かを理解するには、読み進めてください。

また、RSpec の例を外部で定義する必要がある場合は、Shared Example Groupsを使用する必要があります。

于 2010-08-01T15:10:33.323 に答える