使用 rspec 检查错误的枚举
Check for bad enum with rspec
有谁知道如何检查 rspec 中的无效枚举响应?我可以检查以确保枚举不是 nil 而没有错误,但是当我检查以确保错误的枚举值不起作用时,我收到错误。这是两个规格:
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
感谢您的帮助!
您的问题是您需要期望将构建作为过程执行以评估结果。通过将括号更改为大括号来执行此操作,如
中所述
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
有谁知道如何检查 rspec 中的无效枚举响应?我可以检查以确保枚举不是 nil 而没有错误,但是当我检查以确保错误的枚举值不起作用时,我收到错误。这是两个规格:
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
感谢您的帮助!
您的问题是您需要期望将构建作为过程执行以评估结果。通过将括号更改为大括号来执行此操作,如
中所述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