← Back to Upcase

Mocking ActiveResource?


(Russen Guggemos) #1

Assume, for the moment, that ActiveResource isn’t overrated, and that we have an entire app based around it, that consumes JSON from another Rails app. Is there a nice FactoryGirl-like way to mock our models?

I found a 6-yr-old article on mocking ActiveResource:
https://learn.thoughtbot.com/rest+rails+activeresource+resource+tests+testing

Is there a better approach to use, currently?

Also, we fall back to using RestClient when the features of REST are too awesome for ActiveResource to handle.


(Russen Guggemos) #2

Unable to sit idly, I did some further research and found a nice way to combine Webmock with FactoryGirl.

def webmock_stub model
  stub_request(:get, host + model.class.element_path(model.id))
    .with(query: hash_including({}))
    .to_return( body: model.to_json)
end

before do
  user = FactoryGirl.build_stubbed(:user)
  webmock_stub(user)
end

Since User.element_path(1) returns a resource URL like "/users/1.json", this was easy to wrap into a generalized helper method.


(Ben Orenstein) #3

Cool! Thanks for posting the solution you came up with.