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エラー】'0' is not a valid role

Posted at

##環境
Ruby 3.0.2
Rails 6.1.4.1

##状況

enum genre: { mistery: 0, romance: 1 }
factory.rb
FactoryBot.define do
  factory :post do
    user
    
    title { 'first' }
    genre { 0 }
  end
end
rspec.rb
context '記事を追加する際、正しい値の場合' do
  let!(:post) { create(:post) }
  let!(:post_params) { attributes_for(:post, title: 'other') }
  it '記事を追加できること' do
    expect {
     post "/manage/posts/#{post.id}", params: { post: post_params }
    }.to change(Post, :count)
    expect(response).to have_http_status(302)
    expect(post.reload.title).to eq 'other'
  end
end
ArgumentError:
       '0' is not a valid role

employee_paramsにgenreの値は0が渡っていたため、パラメーターが正しくなくDBに追加されずにテストが落ちていた。

> employee_params
=> {:title=>"first",
    :genre=>0}

##解決法

enumを設定しているときのFactoryBotの値は文字列でデータ作成する。

factory.rb
FactoryBot.define do
  factory :post do
    user
    
    title { 'first' }
    genre { 'mistery' }
  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?