使用表null的Rails minitest模型测试:false约束

时间:2017-09-10 19:08:12

标签: ruby-on-rails minitest

我已经开始了一个新的rails 5应用程序:

rails new projectOne --api --database=postgresql

创建了一个用户模型:

rails g model user

使用相应的表迁移:

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :email,              null: false
      t.string :password_digest,    null: false
      t.string   :confirmation_token
      t.datetime :confirmed_at
      t.datetime :confirmation_sent_at
      t.timestamps
    end
  end
end

当我运行以下最小的测试时:

require 'test_helper'

class UserTest < ActiveSupport::TestCase
  test "the truth" do
    assert true
  end
end

输出结果为:

Error:
UserTest#test_the_truth:
ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR:  null value in column "email" violates not-null constraint
DETAIL:  Failing row contains (980190962, null, null, null, null, null, 2017-09-10 18:58:52.08302, 2017-09-10 18:58:52.08302).
: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2017-09-10 18:58:52.083020', '2017-09-10 18:58:52.083020', 980190962)

在控制台中,我可以创建一个空的User对象,并按预期收到上述错误,但我不明白在我的测试中试图创建对象的是什么。我很欣赏如何让这个测试通过的解释和一些建议。

1 个答案:

答案 0 :(得分:1)

命令bundle exec rails g model SomeModel正在调用一堆包含测试生成器的生成器。测试生成器生成测试模板和夹具:

  

Fixtures是样本数据的一个奇特的词。夹具允许你   在测试之前使用预定义数据填充测试数据库   跑。夹具与数据库无关,并以YAML编写。有   每个型号一个文件。

最小的尝试加载环境并使用fixtures填充您的测试数据库,在您的情况下失败。看起来就像你有无效的固定装置。要解决您的问题,请检查forlder test/fixtures并修复或删除您的灯具。

详细了解testing in Rails