[英]How to test adding line to error log by causing rescue statement in rspec
我有這個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
插入了error.txt
?
您可以閱讀您實際上正在寫入的文件
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 })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.