6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FactoryGirl.createのパラメータにActiveRecordのオブジェクトを設定するとActiveRecord::AssociationTypeMismatchが発生した

Last updated at Posted at 2018-08-29

一日中悩んだので、対策を記載しておきます。

例えば、以下リレーション

app/model/user.rb
class user
   has_many :articles
end
app/model/user.rb
class article
   belong_to :user
end

以下Factoryがある場合

spec/factories/user.rb

FactoryGirl.define do
  factory :user, :class => 'User' do
     name '田中'
  end
end

spec/factories/article.rb

FactoryGirl.define do
  factory :article, :class => 'Article' do
    association :user, :factory => :user
  end
end

articleのテストデータを作成する時に、test_userのデータを作成して、articleのassociationである:userにtest_userを指定する。

spec/model/article_spec.rb
describe 'test' do
  let(:test_user){ 
    FactoryGirl.create(
      :user,
      :name => '松本'
) } 
  let(:article) {
    FactoryGirl.create(
      :article,
      :user => test_user
    )
  }
# テスト内容省略
end

ファイル単体ではテスト成功。

rspec spec/model/article_spec.rb

しかし、rake specで全テスト実行したら、 ActiveRecord::AssociationTypeMismatchのエラーが発生した。

     ActiveRecord::AssociationTypeMismatch:
      User(#70278536617000) expected, got User(#70278553470100)

根本原因はわからないが、FactoryGirl.createをする時にオブジェクトではなくidを指定すれば、エラーはなくなった。

spec/model/article_spec.rb
  let(:user){ FactoryGirl.create(:user) } 
  let(:article) {
    FactoryGirl.create(
      :article,
#     :user => user
      :user_id => user.id
    )
  }

FactoryGirlはオブジェクトで渡せるはずではなかったのか。。

全体のテストに影響がでるため、一旦この方法で解決しました。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?