【问题标题】:How to set a stub for all tests?如何为所有测试设置存根?
【发布时间】:2015-03-20 11:46:31
【问题描述】:

在控制器中,我正在使用带有线路的外部地理编码服务:

loc = Location.geocode(@event.raw_location)

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

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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rspec rspec2


    【解决方案1】:

    您应该在您的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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-26
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 2023-04-11
      相关资源
      最近更新 更多