即使从用户模型中删除了电子邮件验证,唯一性验证也会失败?

时间:2018-04-23 14:22:48

标签: ruby-on-rails ruby unit-testing tdd

我遇到了让Rails测试通过的麻烦。

我正在关注Anthony Lewis的 Rails Crash Course:一个严格的Rails开发指南并且已经进行了双重检查&比较了教科书中的代码。此测试旨在创建有效用户,并检查验证是否正常。

所以,我采取了重现错误的步骤:

  1. 打开User.rb模型,删除uniqueness: true行(以帮助诊断问题)。
  2. 运行rake test test/models/user_test.rb
  3. 导致以下错误:

      Error:
            UserTest#test_saves_with_valid_attributes:
            ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: posts.id: INSERT INTO "posts" ("title", "body", "url", "type", "created_at", "updated_at", "id", "user_id") VALUES ('MyString', 'MyText', 'MyString', NULL, '2018-04-23 07:01:37.793314', '2018-04-23 07:01:37.793314', 980190962, 980190962)
    

    即使我从uniqueness:true移除了:email,有人可以解释为什么我仍然会收到唯一性验证错误吗?

    这是我的User.rb的样子:

    class User < ApplicationRecord
        has_many :subscriptions, foreign_key: :follower_id, dependent: :destroy
    
        has_many :leaders, through: :subscriptions 
    
        has_many :reverse_subscriptions, foreign_key: :leader_id, 
        class_name: 'Subscription', dependent: :destroy
    
        has_many :followers, through: :reverse_subscriptions
    
        has_many :posts, dependent: :destroy
        has_many :text_posts, dependent: :destroy
        has_many :image_posts, dependent: :destroy
    
        def following?(leader)
            leaders.include? leader
        end
    
        def follow!(leader)
            if leader != self && !following?(leader)
                leaders << leader
            end
        end
    
        has_secure_password
    
        **validates :email, presence: true, uniqueness: true** 
    
        def timeline_user_ids
            leader_ids + [id]
        end
    
    
    
    end
    

    我的user_test.rb包含的内容:

    require 'test_helper'
    
    class UserTest < ActiveSupport::TestCase
      # test "the truth" do
      #   assert true
      # end
    
      test "saves with valid attributes" do
        user = User.new(
          email: "user@example.com",
          password: "password",
          password_confirmation: "password"
        )
        assert user.save
      end
    end
    

    我感觉它与灯具有关,但文件是Rails 5.1默认值。

1 个答案:

答案 0 :(得分:0)

查看您的邮件错误:

ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: posts.id ...

所以我想嗯......也许post.id与你数据库中的其他一个重复。请再次检查:)