简体   繁体   English

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

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

I have started a new rails 5 application: 我已经启动了一个新的Rails 5应用程序:

rails new projectOne --api --database=postgresql

created a user model: 创建了一个用户模型:

rails g model user

with corresponding table migration: 与相应的表迁移:

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

When I run the following minitest test: 当我运行以下最小测试:

require 'test_helper'

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

The output is: 输出为:

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)

In the console, I can create an empty User object and as expected receive the above error, but I do not understand what is trying to create the object within my test. 在控制台中,我可以创建一个空的User对象,并且按预期会收到上述错误,但是我不理解在测试中试图创建该对象的原因。 I'd appreciate an explanation and some advice of how to get this test to pass. 我希望能得到有关如何通过此测试的解释和建议。

The command bundle exec rails g model SomeModel is invoking a bunch of generators include a test generator. 命令bundle exec rails g model SomeModel正在调用一堆生成器,包括测试生成器。 The test generators generate a test template and fixtures: 测试生成器生成测试模板和固定装置:

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. 夹具是独立于数据库的,并使用YAML编写。 There is one file per model. 每个模型只有一个文件。

The minitest trying to load environment and populate your test database with fixtures, which fails in your case. 尝试加载环境并使用固定装置填充测试数据库的最小测试,在您的情况下会失败。 Look's like you have invalid fixtures. 看起来您的灯具无效。 In order to resolve your issue check the forlder test/fixtures and fix or delete your fixtures. 为了解决您的问题,请检查辅助test/fixtures并修复或删除固定装置。

Read more about testing in Rails . 阅读有关testing in Rails更多信息。

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

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