Stub out address geocoding during RSpec unit test

有些话、适合烂在心里 提交于 2019-12-22 03:55:28

问题


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.

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

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?

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


回答1:


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

Now, you can use any_instance in your tests:

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



回答2:


it's

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

with mocha.



来源:https://stackoverflow.com/questions/5645411/stub-out-address-geocoding-during-rspec-unit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!