Search code examples
ruby-on-railsruby-on-rails-4rspecfactory-botrspec-rails

`raise_record_invalid` using FactoryBot with Rspec in 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


Solution

  • 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 ;)