使用rspec检查错误的枚举
有谁知道如何在rspec中检查无效的枚举响应? 我可以检查以确保枚举不是没有错误,但是当我检查确保坏的枚举值不起作用时,我收到错误。 这些是两个规格:
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
这就是我的模型:
class Question < ActiveRecord::Base enum question_type: [ :multiple_choice ] validates :question_type, presence: true end
这是错误:
Failure/Error: expect(build(:question, question_type: :telepathy)).to have(1).errors_on(:question_type) ArgumentError: 'telepathy' is not a valid question_type
这是我的工厂:
FactoryGirl.define do factory :question, :class => 'Question' do question_type :multiple_choice end end
谢谢您的帮助!
您的问题是您需要执行构建作为proc来评估结果。 通过将括号更改为大括号来执行此操作,如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