0

I am testing with rspecs on model

 u = User.create(email: 'asd@we.com', password: 'asdasdasd', admin: true, firstname: 'qwe', lastname: 'wer', grade: 5, section: 'w', role: 'teacher')
       expect(u).to be_valid

but it raises an exception if role is set to a random value for example "principal" this happens because role is an enum with two possible values "student" and "teacher"

So in this case i cannot use expect(u).to be_valid. I have to catch the exception. The error it throws is

ArgumentError:
       'principal' is not a valid role

So i am wondering what other cases does .create throw an error instead of just populating the errors in model.errors. When should i catch errors? I appreciate any help! Thanks!

kofhearts
  • 3,607
  • 8
  • 46
  • 79
  • Perhaps you may want to see [this question](https://stackoverflow.com/questions/29780121/rails-test-validation-of-enum-fields). – 31piy Jun 10 '17 at 05:19

1 Answers1

1

There is a column in User model with type enum. The enum column in Rails is always raise an error if you're trying to set an invalid value.

The Rails core team explaination:

The current focus of AR enums is to map a set of states (labels) to an integer for performance reasons. Currently assigning a wrong state is considered an application level error and not a user input error. That's why you get an ArgumentError.

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103