RSpec学習メモ [RSpec編] 02_ModulSpec

<テストエラーから学んだこと>

association :userを記載するときは、spec/factories/users.rbも作成する必要がある。

それを作成していなくて以下のようなエラー内容が出ていた。

 

<spec/factories/tasks.rb>

FactoryBot.define do

  factory :task do

    sequence(:title){ |n| "title#{n}" }

    content { "test content" }

    deadline { "1.week.from.now" }

    status { :todo }

    association :user

  end

end

 

<spec/models/task_spec.rb>

require 'rails_helper'

 

RSpec.describe Task, type: :model do

  describe 'validation' do

    it 'is valid with all attributes' do

      task = FactoryBot.build(:task)

      expect(task).to be_valid

      expect(task.errors).to be_empty

    end

  end

end

 

<エラー内容>

1) Task validation is valid with all attributes

     Failure/Error: task = FactoryBot.build(:task)

     

     KeyError:

       Factory not registered: "user"

     # ./spec/models/task_spec.rb:6:in `block (3 levels) in <top (required)>'

     # ------------------

     # --- Caused by: ---

     # KeyError:

     #   key not found: "user"

     #   ./spec/models/task_spec.rb:6:in `block (3 levels) in <top (required)>'

 

Finished in 0.02851 seconds (files took 0.74684 seconds to load)

1 example, 1 failure

 

Failed examples:

 

rspec ./spec/models/task_spec.rb:5 # Task validation is valid with all attributes

 

---------------------------------------------------------------------------------------

 

<解答例から学んだこと>

① sequence(:title, "title_1") ブロックを渡さす第二引数を渡すと、.nextが呼ばれるようになる。(※英字 + 記号 + 数字の時だけ

sequence(:email) { |n| "user_#{n}@example.com" }

 

② spec/rails_helper.rbでconfig.include FactoryBot::Syntax::Methodsを追記することにより、以下のようにrspecのテストコード内でFactoryBotのメソッドを使用する際に、クラス名の指定を省略することができる。

 

# 通常FactoryBotをつけないとメソッドを呼ぶことができない。

task = FactoryBot.create(:task)

 

# 上記の設定を追記することで、FactoryBotの記述が省略できる。

task = create(:task)

 

 

③ it ‘is invalid with a duplicated email’ do

  task = create(:task)

  task_with_duplicated_title = build(:task, title: task.title)

  expect(task_with_duplicated_title).to be_invalid

end

 

上記のようなテストでは、task_with_duplicated_titleのように、その変数が何の役割を持っているのか明示的にすること。