How to use FactoryGirl to create data with has_many through association and some not null column

247 views Asked by At

I have a model like this

class Article < ActiveRecord::Base
  has_many :comments
  has_many :details, :through => :comments
end

class Comment < ActiveRecord::Base
  belongs_to :article
  belongs_to :detail
end

class Detail < ActiveRecord::Base
  has_many :comments
end

and I want to create an article with detail, so that’s what I do

factory :article do
  title "My Title"
  text  "My Text"

  factory :article_with_detail do
    after(:create) do |article|
      article.details << FactoryGirl.create(:detail)
    end
  end
end

factory :detail do
  content "My Detail"
end

It works fine for now, but when I want to add some constraint to my model ‘comment’ that make the commenter column can’t be null

class ChangeCommentCommenterToNotNull < ActiveRecord::Migration
  def change
    change_column :comments, :commenter, :string, :null => false
  end
end

now I run rake spec will got an error says:

ActiveRecord::StatementInvalid:
SQLite3::ConstraintException: NOT NULL constraint failed: comments.commenter: INSERT INTO "comments" ("detail_id", "article_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)

How can I get around with this? Please Help~

1

There are 1 answers

3
caspg On

How does your Comment factory looks? commenter attribute should be set to smth to not be nil.

EDIT: create new factory file Comment in your factories directory (remember to set commenter to smth).

factory :comment do
  commenter "first comment"
  body "Great article!"
  detail
end

https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations