简体   繁体   中英

Rails minitest model test with table null:false constraint

I have started a new rails 5 application:

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. 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. 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. 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.

Read more about testing in Rails .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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