帮助我通过这个测试:
这是一些 rspec 代码的示例,
class User
attr_accessor :count
def initialize
@count = 0
end
# sometimes raises
def danger
puts "IO can be dangerous..."
rescue IOError => e
@count += 1
end
#always raises
def danger!
raise IOError.new
rescue IOError => e
@count += 1
end
end
describe User do
describe "#danger!" do
it "its rescue block always increases the counter by one" do
allow(subject).to receive(:'danger!')
expect {
subject.danger!
}.to change(subject, :count).by(1)
end
end
describe "#danger" do
context "when it rescues an exception" do
it "should increase the counter" do
allow(subject).to receive(:danger).and_raise(IOError)
expect {
subject.danger
}.to change(subject, :count).by(1)
end
end
end
end
我还创建了一个包含这些测试的小提琴,所以你可以让它们通过。请帮我测试一个方法的救援块!
背景:
我原来的问题是这样的:
我有一个方法,如下所示:
def publish!(resource)
published_resource = resource.publish!(current_project)
resource.update(published: true)
if resource.has_comments?
content = render_to_string partial: "#{ resource.class.name.tableize }/comment", locals: { comment: resource.comment_content_attributes }
resource.publish_comments!(current_project, published_resource.id, content)
end
true
rescue Bcx::ResponseError => e
resource.errors.add(:base, e.errors)
raise e
end
我想测试一下resource.errors.add(:base, e.errors)
,实际上是在资源中添加了一个错误。更一般地说,我想在一个方法中测试救援块。
所以我想写这样的代码,
it "collects errors" do
expect{
subject.publish!(training_event.basecamp_calendar_event)
}.to change(training_event.errors.messages, :count).by(1)
end
当然,这会引发错误,因为我在救援区块中重新加注。
我见过一些使用 old 的答案something.stub(:method_name).and_raise(SomeException)
,但 rspec 抱怨这种语法已被弃用。我想使用Rspec Mocks 3.3和allow
语法,但我很难过。