什么时候创建引发错误?
When does create raise error?
我正在模型上使用 rspecs 进行测试
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
但是如果将角色设置为随机值(例如 "principal"),则会引发异常,因为角色是一个枚举,具有两个可能的值 "student" 和 "teacher"
所以在这种情况下我不能使用 expect(u).to be_valid。我必须抓住例外。它抛出的错误是
ArgumentError:
'principal' is not a valid role
所以我想知道在其他情况下 .create 会抛出错误,而不仅仅是填充 model.errors 中的错误。我什么时候应该捕获错误?感谢您的帮助!谢谢!
用户模型中有一列类型为枚举。如果您尝试设置无效值,Rails 中的枚举列总是会引发错误。
Rails核心团队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.
我正在模型上使用 rspecs 进行测试
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
但是如果将角色设置为随机值(例如 "principal"),则会引发异常,因为角色是一个枚举,具有两个可能的值 "student" 和 "teacher"
所以在这种情况下我不能使用 expect(u).to be_valid。我必须抓住例外。它抛出的错误是
ArgumentError:
'principal' is not a valid role
所以我想知道在其他情况下 .create 会抛出错误,而不仅仅是填充 model.errors 中的错误。我什么时候应该捕获错误?感谢您的帮助!谢谢!
用户模型中有一列类型为枚举。如果您尝试设置无效值,Rails 中的枚举列总是会引发错误。
Rails核心团队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.