How can I optionally mock geocoder?

China☆狼群 提交于 2019-12-13 02:23:35

问题


I'd like to be able to mock the results of the geocoder gem in some of my tests.

I use RSpec and Cucumber. In cucumber I'd like to default to mocking the Geocoder results, but be able to turn it back on again by adding a tag. That would be perfect! Something similar for RSpec would be good too. It would speed up my tests enormously.

I know there are some gems out there for doing similar things, e.g. sunspot_test for sunspot. Is there anything similar for geocoder?


回答1:


Im using vcr gem for remote services, check it out! It can be very useful in your situation. github.com/myronmarston/vcr




回答2:


You can use mocha to stub and mock calls. If you do something like (and I'm just making this up because I don't know the GeoCoder syntax):

GeoCoder.get_data(x, y)

And that's something you want to stub out and force to return something else, mocha allows you to do:

GeoCoder.stubs(:get_data).with(x, y).returns(my_own_variable)

And that will make any call to GeoCode.get_data, when passed in x and y, to return your custom variable. However, this stub will last for all subsequent calls during your test, so you can unstub it by calling:

GeoCoder.unstub(:get_data)

And that completely restores that method to normal.

In terms of Rspec, in a teardown block you can unstub. In terms of Cucumber, you can add a tag like @stubs_geocoder before scenarios, and within features/support/env.rb you can add this:

Before('@stubs_geocoder') do
    # add your stub calls
end

After('@stubs_geocoder') do
    # unstub
end


来源:https://stackoverflow.com/questions/9098185/how-can-i-optionally-mock-geocoder

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