@HeRoYo (裕希 吉田)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

FactoryBotを使ってRspecを実行したらエラーが出た

Q&A

Closed

KeyError: Factory not registered を解決したい

Ruby on Railsで映画やドラマの感想を共有できるアプリを作っています。
感想を投稿する機能を実装したのでモデルの単体テストを行いたいのですが
FactoryBotを導入したら、エラーが出てしまいました。

エラー文で検索してみたのですが、解決しなかったので質問いたします。

発生している問題・エラー

Failure/Error: @post = FactoryBot.build(:post)
     
KeyError:
  Factory not registered: "post"
 # ./spec/models/post_spec.rb:5:in `block (2 levels) in <top (required)>'
 # ------------------
 # --- Caused by: ---
 # KeyError:
 #   key not found: "post"
 #   ./spec/models/post_spec.rb:5:in `block (2 levels) in <top (required)>'

該当するソースコード

spec/models/factories/post.rb
FactoryBot.define do
  factory :post do
    title {Faker::Movie.title}
    genre_id { 3 }
    text {Faker::Lorem.sentence}
  end
end
spec/models/post_spec.rb
require 'rails_helper'

RSpec.describe Post, type: :model do
  before do
    @post = FactoryBot.build(:post)
  end

  describe '感想投稿' do
    context '感想が投稿ができる場合' do
      it 'タイトル、ジャンル、内容が存在すると投稿できる' do
      end
    end
    context '感想が投稿できない場合' do
      it 'タイトルが空では投稿できない' do
      end
      it 'タイトルが21文字以上だと投稿できない' do
      end
      it 'ジャンルが空だと投稿できない' do
      end
      it '内容が空だと投稿できない' do
      end
      it '内容が10001文字以上だと投稿できない' do
      end
    end
  end
end
app/models/post.rb
class Post < ApplicationRecord
  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to :genre

  with_options presence: true do
    validates :title, length: { maximum: 20 } # 20文字以下
    validates :text, length: { maximum: 10000 } #1万文字以下
  end

  validates :genre_id, numericality: { other_than: 1, message: "can't be blank"} 
end

自分で試したこと

同様なエラーが出ている記事をいくつか拝見した結果、
2つの解決策が見つかりました。
①ターミナルで「spring stop」を実行する
②spec_helper.rbに記述を追加する

どちらも試してみたのですが、
変わらずRspecを実行するとエラーが出てしまう状況です。

どうか原因と解決策をご教授願えないでしょうか?

0 likes

2Answer

$ rails c
> Post.new

とかまず出来ますか?Postクラス自体が構文エラーとか?(見た感じそんなことはないけど)
genre側の問題とかも考えられるかもしれない。

class Post < ApplicationRecord
  # extend ActiveHash::Associations::ActiveRecordExtensions
  # belongs_to :genre

  # with_options presence: true do
  #   validates :title, length: { maximum: 20 } # 20文字以下
  #   validates :text, length: { maximum: 10000 } #1万文字以下
  # end

  # validates :genre_id, numericality: { other_than: 1, message: "can't be blank"} 
end

一度こうやってそれでもrspecが動かないかどうか確認するとか?

0Like

あと普通はgenreモデル側のfactoryも作ってるはずなので、

FactoryBot.define do
  factory :post do
    title {Faker::Movie.title}
    genre_id { 3 }
    text {Faker::Lorem.sentence}
  end
end

こうではなく

FactoryBot.define do
  factory :post do
    genre
    title {Faker::Movie.title}
    text {Faker::Lorem.sentence}
  end
end

こうするかも。

0Like

Your answer might help someone💌