我有一个Foo
课程。
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
我想通过这个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
如何检查是否已将一行插入error.txt
?
答案 0 :(得分:2)
您可以阅读实际编写的文件
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
另一种方法是检查文件是否已打开:这是
的内容File.should_receive(:open).with("error.txt", "a+", {|f| f.puts e.message })