我有一个带有私有方法的ActiveRecord模型,该方法进行外部HTTP调用。该方法由面向公众的方法调用。出于测试目的,我想存根发出请求的HTTP客户端,因此希望能够注入HTTP客户端并将其设置为ActiveRecord类的属性。我怎样才能做到这一点?或者是否有更好的方法来实现我想要实现的目标?
我想要实现的目标:
# 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
也许我采取了错误的做法。任何建议都将非常感谢!