Search code examples
ruby-on-railsunit-testingruby-on-rails-4

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.

For all other sorts of validations where I include invalid data and then use assert_not these kinds of tests work. Why not in this case? How should I rewrite this model test?


Solution

  • Here's the explanation from Rails team: https://github.com/rails/rails/issues/13971

    If you want to test that invalid values are rejected, use assert_raises to expect the ArgumentError