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
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.
Do the following
rails db:setup
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 ;)