Running a Test Case only when we have internet
TweetSo I have some tests for geocoding, that I want to be run live.
test "geocoding" do record = Address.create!(:address => "Pretty Cottage, Winding Road, Beautiful Country") assert_equal 51.59011, record.latitude assert_equal -2.995398, record.longitude end
Of course, these will fail when there’s no internet.
My choices;
- mock the geocoding API
- let them fail
- only run this test when there’s internet
I chose the latter.
How do I know I have internet connection?
Can I ping google?
system "ping -q -c 1 -t 1 google.com 1> /dev/null" #=> true / false
Complication!
the above works on OSX (where -t1 sets a timeout of 1 second)
but on Linux -t has a different meaning, and -w1 sets the timeout
Compromise: ignore timeouts for the moment
system "ping -q -c 1 google.com 1> /dev/null" #=> true / false
Stick this in a method
def requires_internet!
if can_ping_google?
yield
else
flunk "this test needs to be run when there is internet"
end
end
Now incorporate this into our test.
test "geocoding" do
requires_internet! do
record = Address.create!(:address => "Pretty Cottage, Winding Road, Beautiful Country")
assert_equal 50.0, record.latitude
assert_equal -0.3, record.longitude
end
end
Done.
Here’s the gist. Fork it and make it better!