在两个模型之间关联后,第三个错误:ActiveRecord::RecordInvalid:验证失败:电子邮件已被占用

after association between two models error on a third : ActiveRecord::RecordInvalid: Validation failed: Email has already been taken

我刚刚总结了用户(使用设备管理用户)、wall 和 posts 之间的模型关联。在我尝试用户和墙关联之前,不存在以下错误。 输出失败为:

Post
  Scopes
    .most_recent
      returns all posts ordered from the youngest to the oldest (FAILED - 1)

Failures:

  1) Post Scopes .most_recent returns all posts ordered from the youngest to the oldest
     Failure/Error: let!(:post) { create(:post, created_at: Date.today) }
     ActiveRecord::RecordInvalid:
       Validation failed: Email has already been taken
     # ./spec/models/post_spec.rb:16:in `block (3 levels) in <top (required)>'
     # -e:1:in `<main>'

Failed examples:

rspec ./spec/models/post_spec.rb:20 # Post Scopes .most_recent returns all posts ordered from the youngest to the oldest

我的模特:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Associations
  has_one :wall, dependent: :destroy
end


class Wall < ActiveRecord::Base
  # Associations
  has_many :posts, dependent: :destroy
  belongs_to :user

  # Validations
  validates :user, presence: true
end


class Post < ActiveRecord::Base
  # Associations
  belongs_to :wall

  # Scopes
  scope :most_recent, -> { order(created_at: :desc) }

  # Validations
  validates :content, :wall, presence: true
end

我的post_spec:

require 'rails_helper'

RSpec.describe Post, type: :model do
  let(:post) { build(:post) }

  describe 'Validations' do
    it 'has a valid factory' do
      expect(post).to be_valid
    end

    it { should validate_presence_of(:content) }
  end

  describe "Scopes" do
    let!(:older_post) { create(:post, created_at: Date.today - 2.month) }
    let!(:post) { create(:post, created_at: Date.today) }


    describe ".most_recent" do
      it "returns all posts ordered from the youngest to the oldest" do
        expect(Post.most_recent.first).to eq(post)
        expect(Post.most_recent.last).to eq(older_post)
      end
    end
  end
end

我的post工厂:

FactoryGirl.define do
  factory :post do
    content 'post text'
    wall
  end
end

有什么提示吗?

这只是一个猜测,但您的用户工厂可能不会生成唯一的电子邮件地址。 FactoryGirl 允许您定义一个序列,这将确保您的测试用户的唯一性验证:

FactoryGirl.define do
  sequence :email do |n|
    "person#{n}@example.com"
  end
end

factory :user do
  email
end

您可以在此处的文档中阅读更多内容:http://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md#Sequences