Search code examples
ruby-on-railstestingrspec-rails

When does create raise error?


I am testing with rspecs on model

 u = User.create(email: '[email protected]', 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!


Solution

  • 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.