在 RSpec 单元测试期间剔除地址地理编码 [英] Stub out address geocoding during RSpec unit test

查看:63
本文介绍了在 RSpec 单元测试期间剔除地址地理编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the geocoder gem to add geocoding functionality to one of my Active Record model classes. This works great, but I don't actually want the geocoding to fire during unit tests.

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

I've tried stubbing out the call to geocode by adding this to my RSpec test:

before(:each) 做
User.stub!(:geocode).and_return([1,1])结束

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

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

However, when I run my tests it still appears to be calling out to geocode. What am I doing wrong?

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

FYI, this all works if I stub on the instance level (e.g. some_user.stub! instead of User.stub!).

推荐答案

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

If you want to use stubbing on the instance level, you should use other mocking framework than RSpec’s. It's mocha for example (add the following to spec/spec_helper.rb):

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

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

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

Now, you can use any_instance in your tests:

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

这篇关于在 RSpec 单元测试期间剔除地址地理编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆