Skip to content

Instantly share code, notes, and snippets.

@IanMitchell
Created July 11, 2017 02:53
Show Gist options
  • Save IanMitchell/33d8da9da88194d5c4f3a64e36e3aed3 to your computer and use it in GitHub Desktop.
Save IanMitchell/33d8da9da88194d5c4f3a64e36e3aed3 to your computer and use it in GitHub Desktop.
Minitest Stumbling Block
class A
def b(params)
payload = config.merge(params)
uri = get_endpoint
Net::HTTP.post(uri, payload)
end
end
# Wanted to test A::b by stubbing out Net::HTTP and examining what it was being called with.
# Maybe not the best way of approaching the test, but seemed logical to me. Ended up with the
# following, but struggled finding out how to stub out Net::HTTP and examine the parameters the stub
# was called with. Googling the problem resulted in rspec solutions, but not a lot of Minitest
# tutorials beyond "check out Mocha!" which also didn't have a clearcut answer on how to do this.
@mock = Minitest::Mock.new
@mock.expect(:post, true, [uri, expected_payload])
Net::HTTP.stub :post, ->(uri, payload) { @mock.post(uri, payload) } do
A::b
end
@mock.verify
# Works now though!
@zenspider
Copy link

  1. Original, w/o using unnecessary ivars:
mock = Minitest::Mock.new
mock.expect(:post, true, [uri, expected_payload])
Net::HTTP.stub :post, ->(uri, payload) { mock.post(uri, payload) } do
  A::b
end
mock.verify
  1. You obviously have expected uri and expected_payload for mock, so get rid of mock:
Net::HTTP.stub :post, ->(uri, payload) { ... } do
  A::b
end
  1. Extract proc to make it easier to read:
check = ->(uri, payload) do
  ...
end
Net::HTTP.stub :post, check do
  A::b
end
  1. Check what you want:
check = ->(uri, payload) do
  assert_equal expected_uri, uri
  assert_equal expected_payload, payload
end
Net::HTTP.stub :post, check do
  A::b
end
  1. I'd probably order it differently (just personal taste):
actual_uri = actual_payload = nil
Net::HTTP.stub :post, ->(uri, payload) { actual_uri, actual_payload = uri, payload } do
  A::b
end
assert_equal expected_uri, actual_uri
assert_equal expected_payload, actual_payload

But I still don't get much value out of these types of tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment