Well, slower test suite is a nightmare both in your local machine and in your CI server. If your gem provider has built some Mocking APIs then its cool. But, no mocking API and you are writing Unit Test for your models and controller then beware, do not leave your app making HTTP requests everytime.
What to do?
If you cannot mock your library then mock the damn Internet. Simple enough! you can get going in a couple of minutes. Continue reading
I was developing a movie sorting ruby application which will fetch data from IMDB database. Unfortunately the gem
imdb I have been using to fetch data from IMDB did not have any solution inbuilt to deal with HTTP requests in
test mode. My test suite was insanely slow.
Then, I found that the gem
imdb uses a gem called
fakeweb to fake the HTTP request.
fakeweb requires you to know every URL your suite invokes to fake it. Its quite cumbersome, because you may not always figure which URLs the suite is invoking. So, it was a bad idea for me.
Then I thought about the gem
vcr which I found to be an awesome tool to record all your HTTP request’s responses as fixtures for the future requests.
VCR.configure do |config|
config.cassette_library_dir = "fixtures/vcr_cassettes"
config.hook_into :webmock # or :fakeweb
class VCRTest < Test::Unit::TestCase
response = Net::HTTP.get_response(URI('http://www.iana.org/domains/reserved'))
assert_match /Example domains/, response.body
Every HTTP request you or your code make inside the
code_block passed to `VCR.use_cassette(“synopsis”)` will stubbed with the fixture data if present. If not, it will fetch once and use the same fixture data for future requests.