简体   繁体   English

事务中的 Rspec 测试方法

[英]Rspec testing methods in transaction

I am trying to execute two things inside a transaction and I'm not sure how I should test it in rspec.我试图在一个事务中执行两件事,但我不确定我应该如何在 rspec 中测试它。 My code looks something like this:我的代码看起来像这样:

Implementation:执行:

    def method
      begin
        ActiveRecord::Base.transaction do
          ...some implementation...
          model1.save!
          model2.save!
        end
      rescue => e
          exception_info = {:class => e.class, :message => e.message, :backtrace => e.backtrace}
          @logger.warn("Error. Rolling back.", :exception => exception_info)
      end
    end

Tests:测试:

it "model1 object is not created if model2 fails to save" do
  Model1.any_instance.should_receive(:save).and_raise("model1 save error!!")
  method
  Model2.all.should == []
end

it "" do
  Model2.any_instance.should_receive(:save).and_raise("model2 save error!!")
  method
  Model1.all.should == []
end

I want both the models to be saved or none.我希望两个模型都保存或不保存。 My rspec tests check both the cases but I keep getting errors.我的 rspec 测试检查了这两种情况,但我不断收到错误。 If I add (:requires_new => true) to the transaction, it works.如果我将 (:requires_new => true) 添加到事务中,它就可以工作。 I thought it was meant for nested transactions, not something like this.我认为它是用于嵌套事务的,而不是这样的。 Am I missing something?我错过了什么吗?

ActiveRecord transactions only rollback if an exception is raised. ActiveRecord 事务仅在引发异常时回滚。 Otherwise they persist whatever records were successfully created.否则,它们会保留已成功创建的任何记录。

In your case, you want to use save!在您的情况下,您想使用save! instead of save to interrupt the transaction.而不是save以中断交易。 This will raise an ActiveRecord::RecordInvalid exception which you need to rescue and handle.这将引发您需要挽救和处理的ActiveRecord::RecordInvalid异常。

begin
  ActiveRecord::Base.transaction do
    ...some implementation...
    model1.save!
    model2.save!
  end
rescue ActiveRecord::RecordInvalid
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM