Peter Nixey
Peter Nixey

Reputation: 16565

In RSpec Capybara tests how can you stub your own app's API?

I'm building integration tests that test how the view is built. The architecture of the app is an Angular front end communicating with a Rails API.

I want to test the behaviour of a piece of functionality in Angular that depends on data loaded from the server. I would therefore like to stub that data so that I can guarantee that it's brought back correctly. I know this isn't technically an integration test but it's the front end I'm testing.

What I'd like to be able to do

describe "my front end feature" do 

  # This before block has the data I want to instruct my API to return
    data = [
      {"uid"=>"1", "last_seen_at"=>"2017-05-08T09:24:38"},
      {"uid"=>"2", "last_seen_at"=>"2017-05-08T09:11:07"},
      {"uid"=>"3", "last_seen_at"=>"2017-05-08T08:49:57"}
    ]

    # NB this next line does not work...
    WebMock.stub_request(:any, /\/my_api\/data_resource.*/).to_return(status: 200,
                                                  body: data.to_json)
  end

  it "Should load my stubbed data into the page" do
    login member1
    visit org_path(org)
    # do my test to detect the appropriate content in the page
  end
end

How can you stub your own api?

I know how to use webmock to stub an external API however what I'd like to do is to stub my own API so that when capybara fires up firefox it retrieves my stubbed data rather than hitting the app. Is this possible?

Upvotes: 3

Views: 1325

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49870

As you mentioned this is not something you should really be doing in a feature test. Normally you would configure the data, in your test, using fixtures or factories so that your API is actually run and returns the data you are expecting.

If, however, you insist on continuing with your current plan, the best solution (since it doesn't modify your app code, and runs closest to the idea of feature tests) is a programmable proxy like puffing-billy - https://github.com/oesmith/puffing-billy. It's like WebMock but for requests initiated from the browser instead of internal to your app, and is designed to integrate nicely to the available Capybara drivers.

Upvotes: 1

Related Questions