Stubbing RestClient response in RSpec

I would consider using a gem for a task like this.

Two of the most popular are WebMock and VCR.


Instance doubles are the way to go. If you stub a method that doesn't exist you get an error, which prevents you from calling an un-existing method in production code.

      response = instance_double(RestClient::Response,
                                 body: {
                                   'isAvailable' => true,
                                   'imageAvailable' => false,
                                 }.to_json)
      # or :get, :post, :etc
      allow(RestClient::Request).to receive(:execute).and_return(response)

Using a mock for the response you can do this. I'm still pretty new to rspec and test in general, but this worked for me.

describe "successful POST on /user/create" do
  it "should redirect to dashboard" do
    RestClient = double
    response = double
    response.stub(:code) { 200 }
    RestClient.stub(:post) { response }

    post '/user/create', {
      :name => "dave",
      :email => "[email protected]",
      :password => "another_pass"
    }
    last_response.should be_redirect
    follow_redirect!
    last_request.url.should == 'http://example.org/dave/dashboard'
  end
end