我如何期望使用特定块调用某个方法?

时间:2015-05-27 10:00:50

标签: ruby-on-rails ruby rspec mocking

我希望能够使用rspec测试使用特定块调用的特定gem:

代码看起来像这样

SomeGem.configure do |config|
  config.username = "hello"
  config.password = "world"
end

我写的规范看起来像这样:

it 'sets valid gem configuration' do
  credentials = lambda do |config|
    config.username = "hello"
    config.password = "world"
  end

  expect(SomeGem).to receive(:configure).with(credentials)
end

我得到的错误:

Failure/Error: expect(SomeGem).to receive(:configure).with(credentials)
Wrong number of arguments. Expected 0, got 1.

关于我应该如何测试这个的任何想法?

1 个答案:

答案 0 :(得分:3)

我宁愿尝试断言外部可见效果。假设您有一个SomeGem.configuration方法可用于检索配置的值,那么您可以编写

describe 'configuration block' do
  subject do
    lambda do
      SomeGem.configure do |config|
        config.username = "hello"
        config.password = "world"
      end
    end
  end

  it { is_expected.to change(SomeGem.configuration, :username).to("hello") }
  it { is_expected.to change(SomeGem.configuration, :password).to("world") }
end