Rails,RSpec单元测试用户名失败

时间:2016-10-30 19:26:07

标签: ruby-on-rails validation unit-testing rspec

这里总计n00b。我试图弄清楚如何为我的用户模型编写单元测试。它目前在我的4次测试中都失败了,而且我有一段时间搞清楚原因。

第一次失败就是这条线......

it { should validate_uniqueness_of(:username) }因铁路响应而失败......

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')})通过时,由于空字段而导致用户名单元测试失败?

规格/模型/ 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) }

模型/ user.rb

  validates :username, uniqueness: true, presence: true
  validates_format_of :username, with: /\A[a-zA-Z0-9]+\z/

1 个答案:

答案 0 :(得分:2)

好的,在阅读它时,看起来这可能实际上是与一些边缘情况的shoulda匹配器相关的错误,当在另一列上使用NOT NULL数据库约束测试唯一性时。

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

作为一种解决方法,我建议您明确设置一个有效的模型,并允许shoulda匹配器对要测试的属性执行自己的操作。您可以设置所有应该匹配的主题,如下所示:

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匹配器测试都将使用该对象来运行测试,并且您不应该为您没有测试的属性获取数据库约束问题。