如何使用HABTM关联测试模型?

时间:2015-07-30 19:42:58

标签: ruby-on-rails rspec factory-bot

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

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

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

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

1 个答案:

答案 0 :(得分:1)

创建子工厂可能会更好:

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

但是,这也取决于您的模型中的验证设置。

它没有,它确实:)