2014-10-20 30 views
0

我有一些幫助類存儲在我的spec/support目錄下,我重複使用了許多測試。例如,foo_helper.rb在RSpec 3的輔助類中使用存根時NoMethodError - 但不是RSpec 2?

class FooHelper 
    def self.stub_thing 
    Foo.any_instance.stub(:thing) 
    Foo.any_instance.stub(:thing=) 
    end 
end 

Foo在多項測試用的,所以我只想require ../spec/support/foo_helper.rb在每個天賦我想能夠使用FooHelper.stub_thing。這一切都在RSpec的2.X

已經升級到3.1的RSpec工作得很好,我看到下面的折舊警告:

Using `any_instance` from rspec-mocks' old `:should` syntax without explicitly enabling the syntax is deprecated. Use the new `:expect` syntax or explicitly enable `:should` instead. Called from app/spec/support/foo_helper.rb:4:in `stub_thing'. 

因此,已經增加rspec-actvemodel-mocks我的Gemfile:

gem 'rspec-rails', '~> 3.1' 
group :development, :test do 
    gem 'rspec-activemodel-mocks', '~> 1.0' 
end 

而繼the documentation,我改變了我的代碼:

class FooHelper 
    def self.stub_thing 
    allow_any_instance_of(Foo).to receive(:thing) 
    allow_any_instance_of(Foo).to receive(:thing=) 
    end 
end 

WHI CH,進而導致我的測試中失敗,出現以下錯誤:

Failure/Error: FooHelper.stub_thing 
NoMethodError: 
    undefined method `allow_any_instance_of' for FooHelper:Class 
# ./spec/support/foo_helper.rb:4:in `stub_amount' 
# ./spec/models/parent_model.rb:33:in `block (2 levels) in <top (required)>' 

如何allow_any_instance_of不能被定義,當any_instancestub是?

回答

0

allow_any_instance_of僅在啓用expect語法時按http://www.rubydoc.info/github/rspec/rspec-mocks/RSpec/Mocks/ExampleMethods:allow_any_instance_of啓用。據推測,您將RSpec配置爲僅與較早的should語法一起工作。

+0

感謝您的幫助,但沒有我沒有明確地配置它使用「應該」的語法 - 我不認爲!)我使用由生成的香草'spec_helper.rb'和'rails_helper.rb'運行'rails generate rspec:install' ... – rwb 2014-10-20 14:46:38

0

我剛剛遇到了這個問題。您是否有機會從before :all區塊撥打電話?顯然這是不允許的,因爲它在將它移動到before :each後工作。

希望有幫助!

1

在我們的其中一個應用程序中更新RSpec後,我遇到了這個問題。對於其他任何人遇到它,並且沒有明確選擇should語法的人,只需將extend RSpec::Mocks::ExampleMethods添加到您嘗試使用這些方法的類或模塊的開頭。