Rspec 允许并期望具有不同参数的相同方法

Rspec allow and expect the same method with different arguments

我想测试我的方法 运行s 方法 Temp::Service.运行 在其中两次:

module Temp
  class Service

    def self.do_job
      # first call step 1
      run("step1", {"arg1"=> "v1", "arg2"=>"v2"})


      # second call step 2
      run("step2", {"arg3"=> "v3"})


    end

    def self.run(name, p)
      # do smth

      return true
    end


  end
end

我想用第一个参数 'step2' 测试提供给方法的第二次调用的参数:运行 虽然我想忽略同一方法的第一次调用 :运行 但第一个参数是 'step1'.

我有 RSpec 测试

RSpec.describe "My spec", :type => :request do

  describe 'method' do
    it 'should call' do

      # skip this
      allow(Temp::Service).to receive(:run).with('step1', anything).and_return(true)

      # check this
      expect(Temp::Service).to receive(:run) do |name, p|
        expect(name).to eq 'step2'

        # check p
        expect(p['arg3']).not_to be_nil

      end


      # do the job
      Temp::Service.do_job

    end
  end
end

但是我得到了错误

expected: "step2"
     got: "step1"

(compared using ==)

如何正确使用同一个方法的 allow 和 expect ?

您似乎缺少 .with('step2', anything)

it 'should call' do

  allow(Temp::Service).to receive(:run).with('step1', anything).and_return(true)

  # Append `.with('step2', anything)` here
  expect(Temp::Service).to receive(:run).with('step2', anything) do |name, p|
    expect(name).to eq 'step2' # you might not need this anymore as it is always gonna be 'step2'
    expect(p['arg3']).not_to be_nil
  end

  Temp::Service.do_job
end