繁体   English   中英

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

[英]Rails minitest model test with table null:false constraint

我已经启动了一个新的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对象,并且按预期会收到上述错误,但是我不理解在测试中试图创建该对象的原因。 我希望能得到有关如何通过此测试的解释和建议。

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

夹具是样本数据的花哨词。 夹具允许您在测试运行之前用预定义的数据填充测试数据库。 夹具是独立于数据库的,并使用YAML编写。 每个模型只有一个文件。

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

阅读有关testing in Rails更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM