gpt4 book ai didi

ruby-on-rails - 如何为所有测试设置 stub ?

转载 作者:行者123 更新时间:2023-12-02 04:22:50 25 4
gpt4 key购买 nike

在 Controller 中,我正在使用外部地理编码服务:

loc = Location.geocode(@event.raw_location)

我想为我的所有测试设置一个 stub :

allow(Location).to receive(:geocode).with(nil).and_return({city: nil, state: nil, country: nil})

我应该把这段代码放在哪里?

最佳答案

您应该在 rails_helper.rbspec_helper.rb 中声明一个全局 before(:each)

RSpec.configure do |config|
config.before(:each) do
allow(Location).to receive(:geocode).with(nil).and_return({city: nil, state: nil, country: nil})
end
end

编辑:

此外,如果您只想在涉及地理编码调用的测试中运行此“全局”before(:each),您可以编写:

RSpec.configure do |config|
config.before(:each, geocoding_mock: true) do
allow(Location).to receive(:geocode).with(nil).and_return({city: nil, state: nil, country: nil})
end
end

然后在你的测试中:

describe Location, geocoding_mock: true do
...
end

关于ruby-on-rails - 如何为所有测试设置 stub ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29165788/

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