0

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,995
  • 2
  • 16
  • 25

1 Answers1

0

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

caspg
  • 399
  • 1
  • 6
  • Oh? I don't know where to set up my Comment factory in my case? Since I only create a detail and push (<<) it to my article. What I see the database do it that it will create an empty comment with only article_id and detail_id value, but now I need the comment to have some value in commenter, I don't know where to set it up. – 林鼎棋 Jun 11 '15 at 08:39
  • I create a Comment Factory and change the detail like you said ### factory :comment do commenter "first comment" body "Great article!" end ### but it still doesn't work, now I will get: "NoMethodError: undefined method `comment=' for #" – 林鼎棋 Jun 11 '15 at 10:13
  • Yeah ok, I mixed it up. There should be no `comment` in detail factory, because `Detail` has many comments. Try to add `detail` to Comment factory. – caspg Jun 11 '15 at 10:35