How can I optionally mock geocoder?

2019-08-02 15:29发布

问题:

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