【问题标题】:Add Devise Gem to new Rails project creates test users errors将 Devise Gem 添加到新的 Rails 项目会创建测试用户错误
【发布时间】:2017-01-01 22:33:27
【问题描述】:

我以前没用过 Devise。在这一点上,我的网站只有引导程序、HTML、样式和一些静态页面。我是using this Gemfile 我所有的测试都通过了,直到我运行rake db:migrate。我按此顺序运行了这些步骤。

  • 添加gem 'devise',运行bundle install。 (测试绿色)
  • 运行rails generate devise:install,添加闪光通知(测试绿色)
  • 将 action_mailer 默认行添加到每个文档的开发、测试和生产环境(测试绿色)
  • 运行rails generate devise user(由于待定迁移,测试不会运行)
  • 根据文档检查了新模型,但未更改默认值。
  • 运行rails db:migrate(测试红色)运行它会在我的 db 文件夹中创建一个 test.sqlite3 文件

我现在收到此错误:

ActiveRecord::RecordNotUnique: ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: users.email: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2017-01-01 22:14:19.589023', '2017-01-01 22:14:19.589023', 298486374)

在我所有的测试中。这很奇怪,因为除了检查 HTML 元素是否存在和链接是否有效之外,我还没有创建任何测试,但仍然......

似乎为了通过唯一性约束,我需要一个用户,但我还没有创建任何用户。它也与 SQLite 有关。在我目前的情况下,我怎样才能通过这个测试。我基本上使用 Hartl 教程作为指南。我记得有一个步骤是我们创建假用户,但这不是那个时刻的目的吗?

require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest

  def setup
    @title = "FFP"
  end

  test "should get root" do
    get root_url
    assert_response :success
    assert_select "title", @title
  end
end    

这是我目前的架构。

 ActiveRecord::Schema.define(version: 20170101224251) do

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "provider"
    t.string   "uid"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

end

【问题讨论】:

  • 听起来您在 user.email 字段中已经有两个重复的值,删除其中一个有问题的值,然后重试。
  • 当您尝试将唯一约束添加到已经具有重复值的现有列中,或者尝试将值插入到已经具有该值的字段中时,将发生此错误。
  • 设计为 user.email 添加唯一性。而且我认为您尝试在某个地方创建没有电子邮件地址的用户。
  • @JeffDavenport 感谢您的回复。为了清楚起见,我将当前的架构文件添加到我的问题中。我没有看到有列冲突的地方。我认为我的测试出于某种原因试图创建一个用户,但我看不到在哪里。在我使用 Devise 生成之前没有用户模型
  • @tomtomtom 我同意这似乎是问题所在。我应该以某种方式更新我的test/models/user_test.rb 吗?可能使用test/fixtures/users.yml

标签: ruby-on-rails devise ruby-on-rails-5


【解决方案1】:

您可以通过以下方式更新您的test/fixtures/users.yml 文件来解决此问题。

one:
  email: "mail@mail.com"
#
two:
  email: "mail_2@mail.com"

【讨论】:

    猜你喜欢
    • 2015-04-05
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多