簡體   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