【问题标题】:Testing that a stubbed method is called with a certain input in RSpec测试在 RSpec 中使用特定输入调用存根方法
【发布时间】:2015-05-07 20:20:27
【问题描述】:

我正在对 RSpec 中的控制器方法进行存根,并且存根工作正常,但我如何确保使用特定输入调用该方法,即我传递给调用此存根方法的方法的哈希?

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    您可以使用 expect_to_receive_with_arguments:

    expect(double).to receive(:msg).with(no_args)
    expect(double).to receive(:msg).with(any_args)
    expect(double).to receive(:msg).with(1, any_args) # any args acts like an arg splat and can go anywhere
    expect(double).to receive(:msg).with(1, kind_of(Numeric), "b") #2nd argument can be any kind of Numeric
    expect(double).to receive(:msg).with(1, boolean(), "b") #2nd argument can be true or false
    expect(double).to receive(:msg).with(1, /abc/, "b") #2nd argument can be any String matching the submitted Regexp
    expect(double).to receive(:msg).with(1, anything(), "b") #2nd argument can be anything at all
    expect(double).to receive(:msg).with(1, duck_type(:abs, :div), "b") #2nd argument can be object that responds to #abs and #div
    expect(double).to receive(:msg).with(hash_including(:a => 5)) # first arg is a hash with a: 5 as one of the key-values
    expect(double).to receive(:msg).with(array_including(5)) # first arg is an array with 5 as one of the key-values
    expect(double).to receive(:msg).with(hash_excluding(:a => 5)) # first arg is a hash without a: 5 as one of the key-values
    

    https://github.com/rspec/rspec-mocks#argument-matchers

    https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/setting-constraints/matching-arguments

    【讨论】:

      【解决方案2】:

      #with 方法正是您想要的。
      跟随例子here:
      expect(double).to receive(:stubbed_method).with(hash_argument)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-17
        • 2017-03-27
        • 2016-11-04
        • 1970-01-01
        • 2013-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多