我想测试我在其中运行方法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
我想测试提供给第二次方法调用的参数:用第一个参数运行' 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相同的方法?
答案 0 :(得分:2)
好像你错过了.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