如何在RSpec 3中正确指定类实例的消息期望?

时间:2017-04-19 07:07:50

标签: ruby-on-rails rspec mocking rspec-rails rspec3

我有一个带有名字的Rails类,比方说:Api。 这个类实例有几个方法,我们将它们命名为method1method2

我有一个RSpec测试,它测试调用method1和method2的作业。我需要确保调用method2,但是应该正常执行method1。

Api类看起来像这样:

class Api
  def initialize(params)
    @params = params
  end

  def method1 # should be executed
    ...
  end

  def method2 # expected to be received
    ...
  end
end

在工作期间,使用不同的参数对类进行三次实例化。 所以我提出了一个非常难看的解决方案:

api1        = Api.new('param1')
api2        = Api.new('param2')
api_default        = Api.new
allow(Api).to receive(:new).with(no_args).and_return(api_default)
allow(Api).to receive(:new).with('param1').and_return(api1)
allow(Api).to receive(:new).with('param2').and_return(api2)
expect(api_default).to receive(:method2).once

我不喜欢这个解决方案,因为我只需要检查api_default,但我必须描述所有三个调用。如果我有动态参数怎么办? 怎么能以正确的方式做到这一点?

我使用RSpec 3

谢谢你,对不起我的英语:)

0 个答案:

没有答案
相关问题