使用rspec检查枚举变量是否存在问题

3

有人知道如何在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

谢谢你的帮助!
1个回答

9

你的问题在于需要使用expect将构建作为进程执行以评估结果。通过将括号更改为大括号来实现,具体方法请参考https://dev59.com/eGEi5IYBdhLWcg3wJpgl#21568225

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接