0

我的spec/support目录下存储了许多帮助程序类,我在许多测试中重复使用它们。例如,foo_helper.rb

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 中运行良好

升级到 RSpec 3.1 后,我看到以下折旧警告:

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

并按照文档,我将代码更改为:

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

然后导致我的测试失败并出现以下错误:

 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不能定义,when any_instanceand stubare?!

4

3 回答 3

3

在我们的一个应用程序中更新 RSpec 后,我也遇到了这个问题。对于遇到它的任何其他人,并且没有明确选择should语法,只需添加extend RSpec::Mocks::ExampleMethods到您尝试使用这些方法的类或模块的开头。

于 2015-03-04T19:21:41.587 回答
0

我也遇到了这个问题。你有没有机会从一个before :all街区调用它?显然这是不允许的,因为它在移动到before :each.

希望有帮助!

于 2015-01-21T19:06:44.497 回答
0

allow_any_instance_of仅在启用expect语法时启用,根据http://www.rubydoc.info/github/rspec/rspec-mocks/RSpec/Mocks/ExampleMethods:allow_any_instance_of。据推测,您将 RSpec 配置为仅使用较旧的should语法。

于 2014-10-20T13:47:52.963 回答