gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:18:24 28 4
gpt4 key购买 nike

我想测试我在其中运行两次 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 相同的方法?

最佳答案

好像你错过了 .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

关于ruby-on-rails - Rspec 允许和期望具有不同参数的相同方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44003205/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com