0
0

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 1 year has passed since last update.

エラー:NoMethodError: undefined method `〇〇=' for

Last updated at Posted at 2021-09-30

環境

ruby 2.7.1
Rails 6.1.3.2
RSpec 3.10

状況

Rspec実行時に下記のエラーで怒られた

 NoMethodError:
       undefined method `article=' for #<XXXXX:0x000055d551353cd0>
       Did you mean?  article=
                      article
                      article_id=
spec/factories/users.rb
FactoryBot.define do
  factory :user do
    name { "testuser1" }
    sequence(:email) { |n| "tester#{n}@example.com" }
    password { "testpassword" }
  end
end

spec/factories/articles.rb
FactoryBot.define do
  factory :article do
    user
    title { "sampletitle" }
    content { "samplecontent" }
  end
end
spec/factories/comments.rb
FactoryBot.define do
  factory :comment do
    user
    article
    content { "samplecomment" }
  end
end

原因

FactoryBotのアソシエーションで作成するデータがかぶっていた
(articleとcomment両方にアソシエーションとしてuserが定義されている)

解決方法

アソシエーションがかぶっているcommentのuserのアソシエーションの書き方を変える

spec/factories/comments.rb
FactoryBot.define do
  factory :comment do
    user { article.user }  #articleで作成されたuserを使う
    article
    content { "samplecomment" }
  end
end

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?