Ruby on rails Rspec允许并期望使用具有不同参数的相同方法
我想测试我的方法,该方法在其中运行方法Temp::Service.run两次:Ruby on rails Rspec允许并期望使用具有不同参数的相同方法,ruby-on-rails,rspec3,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
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”运行
虽然我想忽略同一方法的第一个调用:run,但使用第一个参数“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)
期望值将为您检查发送的参数,因此,您不需要执行在块中执行的操作。只需使用
expect(Temp::Service).to receive(:run).with('step2',“arg3”=>“v3”){true}
。我想对第二个参数进行更复杂的检查。所以我用布洛克做的。像这样的“['arg3','arg4'”。每一个都做得很好|期望(p[arg|u good])。而不是|零结束`@MaxIvak没有问题!:)
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