Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to simulate no Internet connection within a Cucumber test?

Part of my command-line Ruby program involves checking if there is an internet connection before any commands are processed. The actual check in the program is trivial (using Socket::TCPSocket), but I'm trying to test this behaviour in Cucumber for an integration test.

The code:

def self.has_internet?(force = nil)
  if !force.nil? then return force
  begin
    TCPSocket.new('www.yelp.co.uk', 80)
    return true
  rescue SocketError
    return false
  end
end

if has_internet? == false
  puts("Could not connect to the Internet!")
  exit 2
end

The feature:

Scenario: Failing to log in due to no Internet connection
  Given the Internet is down
  When I run `login <email_address> <password>`
  Then the exit status should be 2
  And the output should contain "Could not connect to the Internet!"

I obviously don't want to change the implementation to fit the test, and I require all my scenarios to pass. Clearly if there is actually no connection, the test passes as it is, but my other tests fail as they require a connection.

My question: How can I test for this in a valid way and have all my tests pass?

like image 961
xiy Avatar asked Oct 07 '22 23:10

xiy


1 Answers

You can stub your has_internet? method and return false in the implementation of the Given the Internet is down step.

YourClass.stub!(:has_internet?).and_return(false)
like image 196
Flexoid Avatar answered Oct 12 '22 17:10

Flexoid