Why does this Rspec test return an “already sent email”,

This is my specification file, adding a test for the context of “not like user user balance”. I get an error message below.

require 'spec_helper'

describe Sale do 

  context 'after_commit' do

    context 'assignable' do 
      sale = FactoryGirl.create(:sale, earned_cents: 10, assignable: true)
      after { sale.run_callbacks(:commit) }

      it 'updates user balance' do
        sale.user.balance.should == sale.earned
      end
    end

    context 'not assignable' do 
      sale = FactoryGirl.create(:sale, earned_cents: 10, assignable: false)
      after { sale.run_callbacks(:commit) }

      it 'does not updates user balance' do
        sale.user.balance.should_not == sale.earned
      end
    end

  end 
end

And factories

require 'faker'

FactoryGirl.define do
  factory :user do
    email Faker::Internet.email
    password "mypassword"
  end

FactoryGirl.define do
  factory :sale do
    earned_cents 5
    user
  end
end

As /spec/spec_helper.rbI have also had it

require 'database_cleaner'
RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end
end

And this is the error I get.

`save!': Validation failed: Email has already been taken (ActiveRecord::RecordInvalid)

I assume that it is associated with a link userinside SaleFactory, but I do not know why it does not generate a new user for the second test or does not remove it from the database. Any idea?

+4
source share
1 answer

In your factory user, try instead:

factory :user do
  email { Faker::Internet.email }
  password "mypassword"
end
+14
source

All Articles