【问题标题】:Stub out address geocoding during RSpec unit test在 RSpec 单元测试期间存根地址地理编码
【发布时间】:2011-08-04 11:06:44
【问题描述】:

我正在使用geocoder gem 将地理编码功能添加到我的一个 Active Record 模型类中。这很好用,但我实际上不希望在单元测试期间触发地理编码。

我已尝试通过将其添加到我的 RSpec 测试中来消除对地理编码的调用:

之前(:每个)做
User.stub!(:geocode).and_return([1,1]) 结束

但是,当我运行测试时,它似乎仍然在调用地理编码。我做错了什么?

仅供参考,如果我在实例级别存根(例如 some_user.stub!而不是 User.stub!),这一切都有效。

【问题讨论】:

标签: ruby-on-rails ruby rspec geocode stubbing


【解决方案1】:

这是

before(:each) do 
  Address.any_instance.stubs(:geocode).returns([1,1])
end

用摩卡咖啡。

【讨论】:

    【解决方案2】:

    如果你想在实例级别使用存根,你应该使用除 RSpec 之外的其他模拟框架。例如mocha(将以下内容添加到spec/spec_helper.rb):

    Spec::Runner.configure do |config|
      config.mock_with :mocha
    end
    

    http://rspec.info/documentation/mocks/other_frameworks.html

    现在,您可以在测试中使用any_instance

    before(:each) do
     User.any_instance.stub(:geocode).and_return([1,1]) 
    end
    

    【讨论】:

    • 如果您只关心 :geocode 的返回值,这将有效。但地理编码器模块实际上会更新对象的经纬度。我将如何解决这个问题?
    • 事实上,您提供的代码适用于 RSpec >= 2.6,但不适用于 Mocha。
    • @harrism 有点晚了,但我决定像这样处理它,除了主要的地理编码方法之外,还存根经纬度:Restaurant.any_instance.stub(:geocode).and_return([1, 1])Restaurant.any_instance.stub(:latitude).and_return(1)Restaurant.any_instance.stub(:longitude).and_return(1)
    猜你喜欢
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2021-02-16
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多