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 3 years have passed since last update.

【RSpec】KeyError: Factory not registered:を解決した方法

Posted at

#対象者

  • RSpecテストを実施した際にKeyError: Factory not registered:というエラーが出ている方

#目的

  • 上記エラーを解消して、テストを正常に作動させる

#実際の手順と実例
###1.結論(解決策)

aliasを用いて、「spec/factories/user.rb」内のuserに「,aliases: [:follower,:followed] 」と追加して解決

###2.エラー内容と前提

フォロー機能のテスト実行時に出たエラーが下記の通り

スクリーンショット 2021-09-06 14.25.58.png

Factoryに"followed"が登録されていないと予想

下記

model/relationship.rb
class Relationship < ApplicationRecord
  # followerがフォローした人、followedがフォローされた人
  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
end
model/user.rb
class User < ApplicationRecord
  has_many :reverse_of_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy
  has_many :followers, through: :reverse_of_relationships, source: :follower
  has_many :relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
  has_many :followings, through: :relationships, source: :followed
end
spec/factories/relationships.rb
FactoryBot.define do
  factory :relationship do
    association :followed
    association :follower
  end
end
spec/factories/users.rb
FactoryBot.define do
  factory :user do
    name { Faker::Lorem.characters(number: 4) }
    nickname { Faker::Lorem.characters(number: 4) }
    email { Faker::Internet.email }
    introduction { Faker::Lorem.characters(number: 20) }
    password { 'password' }
    password_confirmation { 'password' }
  end
end
spec/models/relationship_spec.rb
require 'rails_helper'

RSpec.describe Relationship, type: :model do
   let!(:relationship) { FactoryBot.create(:relationship) }

  describe "モデルのテスト" do
    it "有効なRelationshipの場合は保存されるか" do
      expect(build(:relationship)).to be_valid
    end
  end
end

###3.エラー原因

Relationship.rbで
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
と記述しているように,アソシエーションに別名をつけている場合はFactoryの方にも別名を付ける必要があります。

なので、users.rbを上記の内容を追加します。

spec/factories/users.rb
FactoryBot.define do
  factory :user, aliases: [:follower,:followed] do
:                 #上記を追加
(中略)
:
end

aliasとは既存のメソッドに対して別名をつけることができるRubyメソッドのひとつです。

Rubyのaliasとalias_methodでメソッドに別名を付ける方法【初心者向け】

これで解決しました!

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?