【问题标题】:How to expect some (but not all) arguments with RSpec should_receive?如何期望 RSpec should_receive 的一些(但不是全部)参数?
【发布时间】:2013-10-07 19:32:30
【问题描述】:
class Foo
  def bar(a, b)
  ...

Foo.should_receive( :bar )

期望使用任何参数调用 bar。

Foo.should_receive( :bar ).with( :baz, :qux )

期望 :baz 和 :qux 作为参数传入。

如何期望第一个参数等于 :baz,而不关心其他参数?

【问题讨论】:

    标签: ruby rspec expectations


    【解决方案1】:

    使用anything 匹配器:

    Foo.should_receive(:bar).with(:baz, anything)
    

    【讨论】:

    • 这行得通。需要注意的是,每个参数都需要一个 anything
    • 我不确定它是否是后来添加的,但是 RSpec 有 any_args 所以对于bar(a, b, c) 你可以做Foo.should_receive(:bar).with(:baz, any_args)
    • 非常感谢@rubyprince,很棒的提示!
    • 我发现任何东西都不起作用,除非它是最后一个参数,这令人沮丧。例如。这不起作用:.with(:baz, anything, :foo)
    • 我将把它放在这里,以展示如何使用对象参数执行此操作:expect(MyObjectRepository).to receive(:create).with({ filename: anything, something_else: some_variable_declared_above })
    【解决方案2】:

    对于 Rspec 1.3,当您的方法接收 hash 作为参数时,anything 不起作用,因此请尝试使用 hash_including(:key => val)

    Connectors::Scim::Preprocessors::Builder.
        should_receive(:build).
        with(
          hash_including(:connector => connector)
          ).
        and_return(preprocessor)
    }
    

    【讨论】:

      【解决方案3】:

      还有另一种方法可以做到这一点,即receive的块形式:https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/block-implementation#use-a-block-to-verify-arguments

      expect(Foo).to receive(:bar) do |args|
        expect(args[0]).to eq(:baz)
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-12
        • 1970-01-01
        • 2021-10-06
        相关资源
        最近更新 更多