ironsand ironsand - 29 days ago 7
Ruby Question

How to test adding line to error log by causing rescue statement in rspec

I have a this

Foo
class.

class Foo
def open_url
Net::HTTP.start("google.com") do |http|
# Do Something
end
rescue Exception => e
File.open("error.txt","a+"){|f| f.puts e.message }
end
end


And I want to test by this Rspec.

require_relative 'foo'

describe Foo do
describe "#open_url" do
it "should put error log if connection fails" do
Net::HTTP.stub(:start).and_return(Exception)
# Check if a line to error.txt is added.
end
end
end


How can I check if a line is inserted to
error.txt
?

Answer

You could read the file you are actually writing

describe Foo do
  describe "#open_url" do
    it "should put error log if connection fails" do
      Net::HTTP.stub(:start).and_raise
      Foo.open_url
      file = File.open("error.txt", "r")
      # ...
    end
  end
end

An alternative would be to check that the file is opened: something along the lines of this

File.should_receive(:open).with("error.txt", "a+", {|f| f.puts e.message })
Comments