如何用 HABTM 协会测试模型?

How to test model with HABTM associations?

我需要测试具有 HABTM 关联的模型。我的工厂看起来像:

FactoryGirl.define do
  factory :article do |f|
    body "Some awesome text"
    after(:build) {|article| article.users = [create(:user)]}
  end
end

以后如何在没有 users 关联的情况下测试 article 创建:

it "is not a valid article without users" do
  article = build(:article, users: []) #doesn't work
  expect(article.valid?).to eq(false)
end

您最好创建一个子工厂:

FactoryGirl.define do
  factory :article do |f|
    body "Some awesome text"

    factory :article_with_users do
      after(:build) {|article| article.users = [create(:user)]}
    end
  end
end

然后测试:

it "don't create article without users associations" do
  article = build(:article) #doesn't work
  expect(article.valid?).to eq(false)
end

it "do create article with users associations" do
  article = build(:article_with_users)
  expect(article.valid?).to eq(true)
end

然而,这也取决于您在模型中的验证设置。

不是,是 :)