Does anyone know how to check for invalid enum responses in rspec? I can check to ensure that the enum isn't nil with no errors but when I check to ensure that a bad enum value doesn't work, I get an error. These are the two specs:
it 'is not valid without question type' do
expect(build(:question, question_type: nil)).to have(1).errors_on(:question_type)
end
it 'is not valid with a bad question type' do
expect(build(:question, question_type: :telepathy)).to have(1).errors_on(:question_type)
end
This is what my model looks like:
class Question < ActiveRecord::Base
enum question_type: [ :multiple_choice ]
validates :question_type, presence: true
end
This is the error:
Failure/Error: expect(build(:question, question_type: :telepathy)).to have(1).errors_on(:question_type)
ArgumentError:
'telepathy' is not a valid question_type
This is my factory:
FactoryGirl.define do
factory :question, :class => 'Question' do
question_type :multiple_choice
end
end
Thanks for the help!
Your issue is that you need expect to execute the build as a proc to evaluate the result. Do this by changing the parentheses to curly brackets, as described in https://stackoverflow.com/a/21568225/1935918
it 'is not valid with a bad question type' do
expect { build(:question, question_type: :telepathy) }
.to raise_error(ArgumentError)
.with_message(/is not a valid question_type/)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With