【发布时间】:2016-10-30 19:26:06
【问题描述】:
这里总共 n00b。我试图弄清楚如何为我的用户模型编写单元测试。它目前在我的 4 次测试中都失败了,我正费时费力地找出原因。
第一次失败是针对这一行的……
it { should validate_uniqueness_of(:username) } 失败,rails 响应...
1) User should require case sensitive unique value for username
Failure/Error: it { should validate_uniqueness_of(:username) }
ActiveRecord::StatementInvalid:
PG::NotNullViolation: ERROR: null value in column "seeking_coach" violates not-null constraint
DETAIL: Failing row contains (1, , , , , a, , , , , null, null, null, null, null, null, 0, null, null, null, null, 2016-10-30 19:17:07.366431, 2016-10-30 19:17:07.366431, f, null, null, null).
: INSERT INTO "users" ("username", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"
为什么在之前的单元测试 (it { should have_valid(:username).when('Groucho', 'Marx')}) 通过时,用户名的单元测试会由于空字段而失败?
spec/models/user_spec.rb
it { should have_valid(:username).when('Groucho', 'Marx')}
it { should_not have_valid(:username).when(nil, '')}
it { should validate_uniqueness_of(:username) }
models/user.rb
validates :username, uniqueness: true, presence: true
validates_format_of :username, with: /\A[a-zA-Z0-9]+\z/
【问题讨论】:
-
能否请您考虑将您的问题分成多个帖子,而不是将它们全部归为一个大问题。人们阅读所有这些内容并回答你的每一个问题可能会让人望而生畏。可以找到拆分它的其他充分理由 here。如果您提供Minimal, Complete, and Verifiable example,您将获得更积极的回应。
-
好建议。我现在将相应地对其进行编辑。谢谢!
-
为什么一个测试被赋予空约束而另一个没有,这有点令人困惑——我唯一能想象的是模型中的 before_action 或数据库中的 before 触发器正在根据用户名设置 seek_coach 的值 - 这可能吗?
标签: ruby-on-rails validation unit-testing rspec