ruby-on-rails 使用Rspec & FactoryBot测试与条件作用域关联的`has_many`时出现奇怪错误

kd3sttzy  于 2023-06-25  发布在  Ruby
关注(0)|答案(1)|浏览(177)

我承认我不擅长使用Rsec和FactoryBot,所以这很可能是由于我缺乏经验,但是当我试图测试一个has_many关联时遇到了一个奇怪的问题,其中未作用域的关联通过了where条件,但作用域的关联是空的,但仍然有正确的计数。
下面是简化的设置:

  • Ruby 2.7
  • Rails 6.0
  • Rspec 3.12
  • FactoryBot 6.2
    型号
class Club < ApplicationRecord
  has_many :members,
    inverse_of: :club,
    dependent: :nullify,
    autosave: true

  has_many :active_members,
    -> { where(active_status_id: [1, 2]) },
    inverse_of: :club,
    dependent: :nullify,
    autosave: true
end

class Member < ApplicationRecord
  belongs_to :active_status,
    inverse_of: :members

  belongs_to :club,
    inverse_of: :members,
    optional: true
end

工厂

FactoryBot.define do
  factory :club do

  end
end

FactoryBot.define do
  factory :member do

  end
end

规格

RSpec.describe Club, type: :model do
  before do
    @club = create(:club)
  end

  describe 'clubs' do
    it 'a club is created' do
      expect(@club).to be_present # pass
    end
  end

  describe 'club members' do
    before do
      @member = create(:member, club: @club, active_status_id: 1)
    end

    context 'a new member' do
      expect(@member.approval_status_id).to eq(1) # pass
      expect(@member.club).to eq(@club) # pass

      expect(@club.members.count).to eq(1) # pass
      expect(@club.members.first).to eq(@member) # pass

      expect(@club.active_members.count).to eq(1) # pass
      expect(@club.active_members.first).to eq(@member) # fail ???

      # And when inspected, `@club.active_members` is: #<ActiveRecord::Associations::CollectionProxy []>
    end
  end
end

为什么@club.active_members.count通过,而@club.active_members.first失败?

gz5pxeao

gz5pxeao1#

你能试试reloading @club吗?
通过调用@club.reload,可以刷新关联并确保新创建的@member包含在@club.active_members中。

相关问题