Alex Smolov
Alex Smolov

Reputation: 1861

Testing that HTTP-request is not made in Rails

What is the easiest way to test if HTTP-request is not made?

Say, I want my application NOT to send an API call to a remote server, if the user doesn't supply a username.

What RSpec test should I write in my Rails app to test that HTTP-request is never made? Can fakeweb help me somehow?

Upvotes: 4

Views: 2702

Answers (3)

Dennis
Dennis

Reputation: 59617

Say we have the following code that makes a conditional request to GitHub's API.

if condition
  user = Octokit.user 'dideler'
end

Using RSpec, you can test that the object doesn't receive the message for the method call.

expect(Octokit).to_not receive(:user)

If it passes, that means the request wasn't made.

Upvotes: 1

Ivan Zamylin
Ivan Zamylin

Reputation: 1748

You should probably try WebMock.
It allows you to check the number of times some url was requested.

assert_requested :post, "http://www.example.com", :times => 0

Upvotes: 8

recneps
recneps

Reputation: 1295

I think I understand what you are asking. You just want to error check to see if a request sent or valid.

If username != blank --> api call else return 'you did not input a username'.

Or you can use the api's return data to check if the request was valid.

I hope this helps.

Upvotes: 0

Related Questions