Помогите мне пройти этот тест:
Вот пример некоторого кода 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
Конечно, это вызывает ошибку, потому что я делаю ре-рейз в блоке спасения.
Я видел несколько ответов, в которых используется старый something.stub(:method_name).and_raise(SomeException)
, но rspec жалуется, что этот синтаксис устарел. Я хотел бы использовать Rspec Mocks 3.3 и синтаксис allow
, но мне тяжело.