简体   繁体   English

如何测试枚举验证?

[英]How to test enum validation?

I have a variable that has a specific set of answer options.我有一个具有一组特定答案选项的变量。 In my model I have:在我的模型中,我有:

validates :article_type,  presence: true
enum article_type:        [ :type1, :type2, :type3 ]

I have the following model test:我有以下模型测试:

test "type test" do
  assert @article.valid?
  @article.article_type= "type1"
  assert @article.valid?
  @article.article_type= "type5"
  assert_not @article.valid?
end

Error: The line @article.article_type= "type5" generates the error: ArgumentError: 'type5' is not a valid article_type .错误: @article.article_type= "type5"行生成错误: ArgumentError: 'type5' is not a valid article_type

For all other sorts of validations where I include invalid data and then use assert_not these kinds of tests work.对于我包含无效数据然后使用assert_not的所有其他类型的验证,这些类型的测试工作。 Why not in this case?为什么不在这种情况下? How should I rewrite this model test?我应该如何重写这个模型测试?

Here's the explanation from Rails team: https://github.com/rails/rails/issues/13971这是 Rails 团队的解释: https ://github.com/rails/rails/issues/13971

If you want to test that invalid values are rejected, use assert_raises to expect the ArgumentError如果要测试无效值是否被拒绝,请使用assert_raises来预期ArgumentError

test "type test" do
  assert @article.valid?
  
  @article.article_type = "type1"
  assert @article.valid?

  assert_raises ArgumentError do
    @article.article_type = "type5"
    assert_not @article.valid?
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM