尝试使用 Rspec 和 FactoryGirl 创建列表时验证失败?

Failing validation when trying to create a list with Rspec and FactoryGirl?

我有一个测试因

而失败
Secret#last_five returns the last 5 secrets when last_five is called
 Failure/Error: let!(:secrets){create_list(:secret, 5)}

 ActiveRecord::RecordInvalid:
   Validation failed: Email has already been taken

错误,我不确定如何修复它。

这是secret_spec.rb中的测试:

describe Secret do
  describe "#last_five" do
    let!(:secrets){create_list(:secret, 5)}
    it "returns the last 5 secrets when last_five is called" do
      expect(Secret.last_five.count).to eq(5)
    end
  end
end

这里是 secret_factory.rb:

FactoryGirl.define do 
  factory :secret do 
    title "Title"
    body "this is the body"
    author
  end

end

这里是 user_factory.rb:

FactoryGirl.define do 
  factory :user, aliases: [:author] do 
    name "Foobar"
    email Faker::Internet.safe_email
    password "password"
    password_confirmation "password"
  end
end

我正在生成一个随机的电子邮件地址,而用户工厂是我唯一使用电子邮件的地方,所以我很困惑我是如何得到电子邮件已经被接受的错误。

感谢您的帮助。

问题是您正在生成随机电子邮件一次。 您需要执行 Faker::Internet.safe_email 代码, 在一个块 内,像这样:

FactoryGirl.define do 
  factory :user, aliases: [:author] do 
    email { Faker::Internet.safe_email }
  end
end

由于您定义了工厂,Faker::Internet.safe_email将仅在用户的工厂定义阶段执行。传递块时,将存储过程而不是字符串。这个包含 Faker::Internet.safe_email 的过程将在您每次执行 create_list(:secret, 5) 时执行,每次都会给您一封新的假电子邮件。

另一种方法是使用 sequence 方法。