1
votes

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
just wild idea. 1. kill your server 2. run rails db:setup 3. run rails db:setup RAILS_ENV=testKick Buttowski
@KickButtowski just tried doing that, didn't help :/anonn023432
even this rails db:setup RAILS_ENV=test?Kick Buttowski
@KickButtowski okay I just tried it with RAILS_ENV and it works. This is weird though, I'll accept it as the answer if you can add that. Do you mind explaining why I had to this though? Tyanonn023432
post the answer for you. hope my explanation is enough for you to start.Kick Buttowski

2 Answers

1
votes

To my defence, I am not so experienced with the FactoryBot.

You have using create in user = FactoryBot.create(:user) , it is going to make record inside your database, so when you are trying to create same record, you will get the error.

  1. Read this for getting more info
  2. check this too

Do the following

  1. Kill your server, so you do not encounter someone is using your database
  2. run rails db:setup
  3. run rails db:setup RAILS_ENV=test

Note: All

rails db:setup

versions will help you to reset your database and run your seed file if there is any.

Hope my explanation was helpful for you to start researching and learning more ;)

0
votes

I know this question is old, but I like to use a different solution, a.k.a. the Faker::Internet portion of the Faker gem.

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="[email protected]">
2.5.7 :014 > user = FactoryBot.build(:user)
 => #<User:0x00007fb938ddadf8 @name="Basil Smitham", @email="[email protected]">
2.5.7 :015 > user = FactoryBot.build(:user)
 => #<User:0x00007fb938de16a8 @name="Mr. Winfred Daugherty", @email="[email protected]">
2.5.7 :016 > user = FactoryBot.build(:user)
 => #<User:0x00007fb939bd2168 @name="Elodia Bartell PhD", @email="[email protected]">
2.5.7 :017 >