【问题标题】:Rspec and commit callback giving an incorrect resultRspec 和提交回调给出不正确的结果
【发布时间】:2018-01-26 23:58:24
【问题描述】:

我有一个用户和角色模型:

class User < ApplicationRecord

  has_and_belongs_to_many :roles
  validates :roles, presence: true, on: :save
  after_create_commit :assign_role

  private

  def assign_role
    self.roles << Role.client if roles.empty?
  end
end

class Role < ApplicationRecord

  has_and_belongs_to_many :users
  validates :name, presence: true, uniqueness: true
  scope :client, -> { where(name: :client) }
end

我无法通过以下 Rspec:

  describe '#assign_role' do
    context 'when creating a new user' do
      it 'is triggered', test: true do
        user = build(:user)
        expect(user).to receive(:assign_role)
        user.run_callbacks(:commit)
      end
    end
  end
(#<User id: nil, email: "tester1@example.com", created_at: nil, updated_at: nil>).assign_role(*(any args))
 expected: 1 time with any arguments
 received: 0 times with any arguments

我知道该方法不会被调用,因为我将 binding.pry 放入方法中。

但是,如果我将模型中的回调更改为 after_create 并且 :create 在 rspec 测试中它可以工作

describe '#assign_role' do
    context 'when creating a new user' do
      it 'is triggered', test: true do
        user = build(:user)
        expect(user).to receive(:assign_role)
        user.run_callbacks(:create)
      end
    end
  end

我什至尝试使用self.use_transactional_tests = false 关闭事务测试,但它不会改变结果。 我想使用 after_create_commit 而不是 after_create。

我怎样才能让这个测试通过?

rspec 3.7,rails 5.2.beta2

【问题讨论】:

  • 构建是拯救用户还是仅仅构建它?
  • 只是构建它。即使我将其更改为 create(:user) 我也会得到相同的错误结果。
  • 如何为测试模式设置数据库?如果它设置为回滚每个测试,它可能根本不会提交。
  • 但是这不是在测试过程中发生的,所以测试后回滚不会影响它吧?
  • 我看错了你说的。我的意思是,如果事务包装了测试并在测试后回滚,那么它永远不会提交,因此没有提交钩子。

标签: rspec ruby-on-rails-5


【解决方案1】:

请试试这个宝石 gem "test_after_commit" 为此,您可能会想,“这很奇怪。为什么我必须使用一个完全独立的 gem 来测试 Rails 附带的回调?它不应该自动发生吗?”

你是对的。真奇怪。但它不会长时间保持怪异。

一旦 Rails 5 更新,您将不必担心test_after_commit

please see this link

【讨论】:

  • 只有 Rails
猜你喜欢
  • 2013-06-21
  • 2020-11-27
  • 2012-08-27
  • 2017-12-14
  • 2019-03-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多