lostisland / faraday

Simple, but flexible HTTP client library, with support for multiple backends.
https://lostisland.github.io/faraday
MIT License
5.72k stars 972 forks source link

Support Proc type for stubbed request body #1436

Closed yykamei closed 2 years ago

yykamei commented 2 years ago

Description

Previously, the Faraday testing adapter compared the request body to the stubbed body just by calling #== if the stubbed body is present. Sometimes, I want to check the equality between request and stubbed body in more advanced ways. For example, there is a case that I want to check only the parts of the body are actually passed to Faraday instance like this:

stubs = Faraday::Adapter::Test::Stubs.new do |stub|
  stub.post('/foo', '{"name:"YK","created_at":"ANY STRING IS OK"}') { [200, {}, ''] }
end
connection.post('/foo', JSON.dump(name: 'YK', created_at: Time.now))
stubs.verify_stubbed_calls

In this case, it's difficult to make tests always pass with "created_at" because the value is dynamic. So, I came up with an idea to pass a proc as a stubbed value and compare bodies, inside the proc:

stubs = Faraday::Adapter::Test::Stubs.new do |stub|
  check = -> (request_body) { JSON.parse(request_body).slice('name') == { 'name' => 'YK' } }
  stub.post('/foo', check) { [200, {}, ''] }
end
connection.post('/foo', JSON.dump(name: 'YK', created_at: Time.now))
stubs.verify_stubbed_calls

I believe this would be flexible but compatible with the previous behavior.

yykamei commented 2 years ago

Thank you 😄 I applied your suggestions as well as fixed problems RuboCop detected. I will rebase this PR if it's needed.