模型上的方法在 rspec 测试期间返回空,即使它应该有一个值

method on model returning empty during rspec tests even though it should have a value

我正在进行以下 rspec 测试以测试我的“#clubs”方法

context "#clubs" do
  it "returns the users associated Clubs" do
    club = create(:club)

    user = club.host

    expect(user.clubs).to contain(club)
  end
end

我的用户模型中的方法:

class User < ActiveRecord::Base
  has_many :host_clubs, :class_name => 'Club', :inverse_of => :host
  has_and_belongs_to_many :volunteer_clubs, :class_name => 'Club', :inverse_of => :volunteers

  def clubs
    [host_clubs, volunteer_clubs].flatten
  end
end

当我 运行 测试并使用 p club.host 时,它 returns 用户如预期的那样,但是我不明白为什么调用 user.clubs => [] returns空数组。这是上下文的工厂。

factory :host, class: User do |f|
  f.first_name { Faker::Name.first_name }
  f.last_name { Faker::Name.last_name }
  f.email { Faker::Internet.email }
  f.password { Faker::Internet.password }
  f.role { "host" }
  f.onboarded_at { Date.today }

  after(:create) do |host|
    host.confirm_email_address
  end
end

factory :club, class: Club do |f|
  f.venue_type { "Primary school" }
  f.name { Faker::Company.name }
  f.address_1 { Faker::Address.street_address }
  f.city { Faker::Address.city }
  host
end

谁能告诉我为什么它可能不会返回记录?

值得注意的是,我是在创建方法后添加此测试的。在控制台中,该方法的行为符合预期。

(将我的评论作为带有附加信息的答案)

尝试 user.reload,然后期待测试中的结果解决此问题。

这是因为 club 对象是独立于 user 创建的。这通常发生在 rspec 测试中。