【问题标题】:How can I expect that a certain method is called with a specific block?我怎么能期望使用特定块调用某个方法?
【发布时间】:2015-05-27 10:00:49
【问题描述】:

我希望能够使用 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.

关于我应该如何测试这个有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby rspec mocking


    【解决方案1】:

    我宁愿尝试断言外部可见的效果。假设您有一个 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
    

    【讨论】:

    • 感谢您为我指明正确的方向。我改用代码expect(SomeGem.username).to eq 'hello'
    • 这个语法不行,因为is_expected只是expect(subject),而不是expect { subject },你必须明确写出来。
    猜你喜欢
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2021-01-24
    • 2020-03-18
    • 1970-01-01
    相关资源
    最近更新 更多