0
1

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エラー】Could not find a valid mapping for

Last updated at Posted at 2021-10-05

##環境
Ruby 3.0.2
Rails 6.1.4.1
devise 4.8.0

##状況
Rspec実行時に下記のエラーで怒られた
(deviseのテスト設定済)

Failure/Error: sign_in user
     
     RuntimeError:
       Could not find a valid mapping for #<Employee id: ...>
app/models/user.rb
class User < ApplicationRecord
  has_one :employee, dependent: :nullify
end
app/models/employee.rb
class Employee < ApplicationRecord
  belongs_to :user, optional: true
end
spec/factories/employees.rb
FactoryBot.define do
  factory :employee, aliases: [:user] do
    firstname { "test" }
    lastname { "employee" }
    sequence(:number) { |n| "1#{n}" }
    sequence(:email) { |n| "tester#{n}@example.com" }
  end
end
spec/requests/XXXXX_spec.rb
RSpec.describe "/XXXXX", type: :request do
  describe 'GET /XXXXX' do
    let!(:user) { create(:employee) }
    subject { get '/XXXXX' }

    before do
      sign_in user
      subject
    end
    it 'ログインしている従業員を取得すること' do
      expect(response).to have_http_status(200)
    end
  end
end

##解決方法

原因:factorybotでuserを作成していないから。employeeのエイリアスとしてuserを指定したら行けると思っていた

spec/factories/users.rb
FactoryBot.define do
  factory :user do
    name { 'test employee' }
    sequence(:email) { |n| "tester#{n}@example.com" }
  end
end
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?