如何为所有测试设置存根?
How to set a stub for all tests?
在控制器中,我正在使用外部地理编码服务:
loc = Location.geocode(@event.raw_location)
我想为我的所有测试设置一个存根:
allow(Location).to receive(:geocode).with(nil).and_return({city: nil, state: nil, country: nil})
我应该把这段代码放在哪里?
您应该在 rails_helper.rb
或 spec_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
编辑:
另外,如果你想 运行 这个 'global' 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
在控制器中,我正在使用外部地理编码服务:
loc = Location.geocode(@event.raw_location)
我想为我的所有测试设置一个存根:
allow(Location).to receive(:geocode).with(nil).and_return({city: nil, state: nil, country: nil})
我应该把这段代码放在哪里?
您应该在 rails_helper.rb
或 spec_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
编辑:
另外,如果你想 运行 这个 'global' 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