Rspec passes test only for one time

In my application I’m using devise for authentication and rspec, capybara for testing. Here are my files

new_student_spec.rb

require ‘rails_helper’

require_relative ‘…/support/new_student_form_spec’

require_relative ‘…/support/login_form_spec’

feature ‘New Student’, type: :feature do

let(:login_form) { LoginForm.new }

let(:new_student) { NewStudentForm.new }

let(:user) { FactoryGirl.create(:user) }

background do

login_form.visit_login_form.fill_form_as(user)

end

scenario ‘fill new student details’ do

new_student.visit_dashboard_page

end

end

new_student_form_spec.rb

class NewStudentForm

include Capybara::DSL

def visit_dashboard_page

visit(‘/dashboard’)

self

end

end

login_form_spec.rb

class LoginForm

include Capybara::DSL

def visit_login_form

visit(‘/users/sign_in’)

self

end

def fill_form_as(user)

fill_in(‘Email’, with: user.email)

fill_in(‘Password’, with: user.password)

click_on(‘Submit’)

self

end

end

Factory (users.rb)

FactoryGirl.define do

factory :user do

transient do

skip_confirmation true

end

sequence(:email) { |n| “email#{n}@example.tld” }

password ‘sceretsceret’

password_confirmation ‘sceretsceret’

before(:create) do |user, evaluator|

user.skip_confirmation! if evaluator.skip_confirmation

end

end

end

Whenever I run ‘bin/rspec’ on above test it passes true only for one time. If I tried to run it one more time it generate following error

  1. New Student fill new student details Failure/Error: let(:user) { FactoryGirl.create(:user) }

    ActiveRecord::RecordInvalid: Validation failed: Email has already been taken

    ./spec/features/new_students_spec.rb:9:in `block (2 levels) in <top (required)>’

    ./spec/features/new_students_spec.rb:12:in `block (2 levels) in <top (required)>’

-e:1:in `’

Where I’m going wrong?

Your test database isn’t being cleared after each test run. Normally this problem is solved by running each test in a transaction which is rolled back at the completion of each test. You can enable this in RSpec with the use_transactional_fixtures option.

Alternatively, check out the database_cleaner gem.

Thanks above gem works for me :slight_smile: