I have an ActiveRecord model with a private method which makes an external HTTP call. This method gets called by a public facing method. For testing purposes, I would like to stub the HTTP client which makes the request, and for this reason would like to be able to inject the HTTP client and set it as an attribute of the ActiveRecord class. How can I do this? Or is there perhaps a better way to do what I am trying to achieve?
For example:
# in my models:
class Model < ActiveRecord::Base
def public_facing_method
...
res = make_external_call
...
end
private
def make_external_call
@client.post(...) # client is injected on init (HTTParty in my case)
end
end
# in my tests:
class ModelTest < ActiveSupport::TestCase
test "Model#public_facing_method should work"
stub_client = MyStubHTTPClient
# is below possible? + would it work in all cases? (ie: when fetching from db)
instance = Model.new(..., stub_client)
instance.public_facing_method
...
end
end
Maybe I am taking the wrong approach. Any suggestions will be very much appreciated!
Aucun commentaire:
Enregistrer un commentaire