`raise_record_invalid` using FactoryBot with Rspec in Rails

时间:2018-03-09 19:16:08

标签: ruby-on-rails ruby-on-rails-4 rspec factory-bot rspec-rails

I'm using FactoryBot to create fake data for my Rspec tests. My factory for the users is as follows:

FactoryBot.define do
  factory :user do
    sequence(:name) { |n| "User#{n}" }
    sequence(:email) { |n| "user#{n}@email.com" }
  end
end

Creating a user creates a client automatically in my User model as an after action:

def initialize_client
  self.client = self.build_client
  self.client.setup_stripe
  self.save
end 

And I have a factory for client as:

FactoryBot.define do
  factory :client do
    user
  end
end

I created an Rspec file to test if the client gets build properly on creating a User as:

describe User, type: :model do
  user = FactoryBot.create(:user)
end

But this raises the error:

raise_record_invalid': Validation failed: Email has already been taken (ActiveRecord::RecordInvalid)

Even though running FactoryBot.create(:user) creates the Client and User as accepted. I'm not sure what I need to change at this point

2 个答案:

答案 0 :(得分:1)

  

为了我的辩护,我对FactoryBot不太熟悉。

您在create中使用user = FactoryBot.create(:user),它将在您的数据库中创建记录,因此当您尝试创建相同的记录时,您将收到错误。

  1. Read this for getting more info
  2. check this too
  3. 执行以下操作

    1. 杀死您的服务器,这样您就不会遇到有人使用您的数据库
    2. 运行rails db:setup
    3. 运行rails db:setup RAILS_ENV=test
    4. 注意:全部

        

      rails db:setup

      版本将帮助您重置数据库并运行种子文件(如果有)。

      希望我的解释有助于您开始研究并了解更多信息;)

答案 1 :(得分:0)

我知道这个问题很旧,但是我喜欢使用另一种解决方案,也就是Faker宝石的Faker::Internet部分。

FactoryBot.define do
  factory :user do
    name { Faker::Name.name }
    email { Faker::Internet.safe_email(name: name) }
  end
end
2.5.7 :013 > user = FactoryBot.build(:user)
 => #<User:0x00007fb93a19f690 @name="Warner Hayes", @email="warner.hayes@example.net">
2.5.7 :014 > user = FactoryBot.build(:user)
 => #<User:0x00007fb938ddadf8 @name="Basil Smitham", @email="smitham_basil@example.com">
2.5.7 :015 > user = FactoryBot.build(:user)
 => #<User:0x00007fb938de16a8 @name="Mr. Winfred Daugherty", @email="daugherty.mr.winfred@example.com">
2.5.7 :016 > user = FactoryBot.build(:user)
 => #<User:0x00007fb939bd2168 @name="Elodia Bartell PhD", @email="bartell.elodia.phd@example.com">
2.5.7 :017 >