为什么这段代码不能以事务方式运行?

时间:2011-08-03 17:27:31

标签: ruby-on-rails transactions

我想要销毁与特定用户有关的所有问题。有些问题虽然受到保护,但可能会阻止自己被销毁并引发异常。

我希望以下代码可以销毁所有问题,但不会销毁任何问题 - 如果其他问题中存在受保护的问题则不会回滚先前的销毁操作 - 为什么会这样?

class User < ActiveRecord::Base
 ...

  Questions.transaction do
    # protected questions will raise a runtime exception
    Questions.destroy_all(:user_id => self.id)
  end
end

1 个答案:

答案 0 :(得分:2)

Grrr,刚才意识到我之前遇到过这个问题,浪费了一大堆时间,然后再搞清楚了。

问题是测试是在RSpec中完成的,RSpec本身使用事务并从代码中删除事务功能(任何人都可以从RSpec团队中读取这些内容 - 在解析代码时发出警告会很棒包含交易 - ty!)。

为了使事务在RSpec中工作,请将其包装在以下代码中:

describe "the set of cases you want to address" do

  # make sure this next line is contained within a describe block or it'll affect everything
  self.use_transactional_fixtures = false

  after(:each) do
    # destroy all objects you created (since RSpec won't roll them back for you)
    # use delete rather than destroy to force removal
    User.delete_all
    Question.delete_all
  end

  it "should not destroy any questions when one fails to be destroyed" do
    # assuming one of the questions throws an error on being destroyed
    expect{
      @user.destroy
    }.to change{ Question.all.count }.by(0)
  end
end