在 Cucumber 测试中模拟没有 Internet 连接的最佳方法是什么?

xiy*_*xiy 5 ruby command-line integration-testing cucumber

我的命令行 Ruby 程序的一部分涉及在处理任何命令之前检查是否有互联网连接。程序中的实际检查是微不足道的(使用 Socket::TCPSocket),但我正在尝试在 Cucumber 中测试此行为以进行集成测试。

编码:

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
Run Code Online (Sandbox Code Playgroud)

特点:

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!"
Run Code Online (Sandbox Code Playgroud)

我显然不想更改实现以适应测试,并且我要求我的所有场景都通过。显然,如果实际上没有连接,则测试按原样通过,但我的其他测试由于需要连接而失败。

我的问题:如何以有效的方式对此进行测试并让我的所有测试都通过?

Fle*_*oid 4

您可以存根您的has_internet?方法并在步骤的实现中返回 false Given the Internet is down

YourClass.stub!(:has_internet?).and_return(false)
Run Code Online (Sandbox Code Playgroud)