Rails minitest 模型测试 table null:false 约束

Rails minitest model test with table null:false constraint

我已经开始了新的 rails5 申请:

rails new projectOne --api --database=postgresql

创建了一个用户模型:

rails g model user

与相应的 table 迁移:

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

当我运行进行以下minitest测试时:

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 对象并按预期收到上述错误,但我不明白是什么试图在我的测试中创建该对象。对于如何通过此测试的解释和一些建议,我将不胜感激。

命令 bundle exec rails g model SomeModel 正在调用一组生成器,包括一个测试生成器。测试生成器生成测试模板和固定装置:

Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and written in YAML. There is one file per model.

minitest 试图加载环境并使用固定装置填充测试数据库,但在您的情况下失败了。看起来你有无效的固定装置。为了解决您的问题,请检查 forlder test/fixtures 并修复或删除您的设备。

详细了解 testing in Rails