Home>

I'm having trouble with FactoryBot.
I'm getting an error in RSpec's system specs and I don't know the cause.

I had a problem trying to test if I was able to log in successfully with RSpec's System spec.
At firstbeforesoFactoryBot.createI created user data in db and tried to test the login procedure, but an error occurred.

require'rails_helper'
RSpec.describe "User login", type :: system do
  before do
    @user = FactoryBot.create (: user)
  end
..
..
..
Failure/Error: @user = FactoryBot.create (: user)
     ActiveRecord :: RecordInvalid:
       Validation failed: Email address already exists
What I tried

Only one user factory is created in the spec directory.

rails console --sandboxWhen I checked in, there was no duplicate email address, but when I quit the console and rolled back, I found that the user's id was abnormal.
First on the consoleFactoryBot.create (: user)When I created a user with, the id is 10, roll back and try againFactoryBot.create (: user)When I created a user with, the id was 11.
User.allWhen all users are displayed with, it becomes 1 ... 10 at first, but when it is rolled back and a user is created again, it becomes 1 ... 9, 11 and id = 10 disappears, and when it is done again, 1. It becomes .9, 12, and 10 and 11 disappear.
In other wordsrails console --sandboxIn the pastFactoryBot.create (: user)Only the id of the user created in was omitted.

somewhereFactoryBot.create (: user)I wonder if RSpec got a validation error because the data created in step 1 remains. I thought, but since I am a beginner, I have no idea what the cause is and where the problem is.

You can use a sequence in FactoryBot to generate a unique email address and I think this test will pass, but I'd like to fix it here as long as I know there's an obvious glitch.

Could anyone lend me some wisdom to solve this problem?

Supplementary information (FW/tool version, etc.)

The environment is as follows
Mac OS Catalina 10.15.7
Ruby 2.7.1
Rails 6.0.3.3
FactoryBot 6.1.0

The factory is as follows.

FactoryBot.define do
  factory: user do
    name {"factory_user"}
    email {"[email protected]"}
    password {"password"}
    password_confirmation {"password"}
  end
end