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

Max*_*vak 5 ruby-on-rails rspec3

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

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
Run Code Online (Sandbox Code Playgroud)

我想测试提供给方法的第二次调用的参数:使用第一个参数“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
Run Code Online (Sandbox Code Playgroud)

但我有错误

expected: "step2"
     got: "step1"

(compared using ==)
Run Code Online (Sandbox Code Playgroud)

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

Jay*_*rio 4

看来你错过了.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
Run Code Online (Sandbox Code Playgroud)