【问题标题】:Check for bad enum with rspec使用 rspec 检查错误的枚举
【发布时间】:2015-03-22 18:41:15
【问题描述】:

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

感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails ruby rspec enums


    【解决方案1】:

    您的问题是您需要将构建作为 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      • 2012-08-27
      相关资源
      最近更新 更多