OUR BLOG

Thoughts on development, design and the world we live in.



Rails3, RSpec2 and WebMock

By sarah in Uncategorized. Posted on May 9th

Yesterday we were deep in the middle of coding using RSpec 2 and Rails 3 and needed to verify that a method made a specific http request. I happily discovered WebMock, which appears to be a next generation FakeWeb. Originally developed by Bartosz Blimke, I was happy to see that Sam Phillips had it working with Rspec 2 and Rails 3.

I found the following posts helpful:
RSpec 2 on Rails 3
using bundler with Rails 3

Here’s what I did to set it up (using rvm, which I highly recommend):
[code]
rvm gemset create rails3
rvm use 1.8.7@rails3
gem install rails --pre
gem install rspec-rails --pre
gem install sqlite3-ruby
rails rails3_webmock
cd rails3_webmock/
vi Gemfile

group :test do
gem "rspec", "2.0.0.beta.8"
gem "rspec-rails", "2.0.0.beta.8"
gem "webmock", :git => "git://github.com/samdanavia/webmock.git"
end

rails g rspec:install
exist lib
create lib/tasks/rspec.rake
exist config/initializers
create config/initializers/rspec_generator.rb
create spec
create spec/spec_helper.rb
create autotest
create autotest/discover.rb

bundle install

add these lines to spec/spec_helper:
require 'webmock/rspec'
include WebMock
[/code]

We wrote the following little test to test how to write a spec that verifies that an http request happens:

[code]
require 'spec_helper'

class Thing
def self.call(uri_string)
uri = URI.parse("http://www.google.com")
result = Net::HTTP.get(uri)
end
end

describe Thing do
it "should call a net API" do
uri_string = "http://www.google.com"
stub_request(:get, uri_string).to_return(:body => "something")
Thing.call(uri_string).should == "something"
WebMock.should have_requested(:get, uri_string)
end
end
[/code]

I put it in spec/lib and can run it with:
[code]
spec spec/lib/thing_spec.rb
[/code]

Note: I don’t need to call “bundle exec” with rspec to ensure that I use the versions specified in the bundle. [Update from@wycats spec_helper loads config/environment.rb which loads application.rb which calls Bundler.setup -- nice.]

Special thanks to @zakkap for the opportunity to dive into Rails 3 on a real project.

By sarah | Posted in Uncategorized | Tagged , , , | Comments (2)

2 Comments

  1. Posted May 9, 2010 at 3:32 pm | Permalink

    Glad you found my fork useful - amazed that you found it! :)

  2. Bartosz Blimke
    Posted May 13, 2010 at 4:47 pm | Permalink

    I just released new WebMock 1.2.0. It includes Sam’s changes for RSpec 2.x compatibility and it preserves backward RSpec 1.x compatibility.

Post a Comment

Your email is never shared. Required fields are marked *

*
*