【问题标题】:Rails, RSpec unit test failing for usernameRails,用户名的RSpec单元测试失败
【发布时间】: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


【解决方案1】:

好的,仔细阅读后,这实际上可能是一个与某些极端情况下的 shoulda 匹配器相关的错误,当在不同列上使用 NOT NULL 数据库约束测试唯一性时。

https://github.com/thoughtbot/shoulda-matchers/issues/600

作为一种解决方法,我建议您明确设置一个有效模型并允许应该匹配器在要测试的属性上做自己的事情。您可以像这样设置所有应该匹配器都应该使用的主题:

describe User do
  subject { User.new(
    username: 'username',
    seeking_coach: 'coach',
    #
    # set other valid attributes here
    #
  )}

  it { should have_valid(:username).when('Groucho', 'Marx')}
  it { should_not have_valid(:username).when(nil, '')}
  it { should validate_uniqueness_of(:username) }
end

当然,如果你使用的是FactoryGirl,并且有一个可以构建有效用户的用户工厂,那么你可以简单地使用:

subject { FactoryGirl.build(:user) }

现在所有的 shoulda 匹配器测试都将使用该对象来运行测试,并且您不应该为您未测试的属性遇到数据库约束问题。

【讨论】:

  • 可能您的其他问题与此有关,但如果不是,请发布一个新问题并保持原样:)
  • 这修复了用户名唯一性验证!谢谢!我现在正在研究其他问题。希望这会有所帮助。
猜你喜欢
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
相关资源
最近更新 更多