为什么这个Rspec测试返回“已经发送电子邮件”

时间:2013-10-25 00:47:44

标签: ruby-on-rails rspec factory-bot

这是我的spec文件,当为上下文添加测试时“不是可单独更新用户余额”我收到以下错误。

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

和工厂

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

/spec/spec_helper.rb我也有了这个

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

这是我得到的错误。

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

我猜它与user Factory中的Sale引用有关,但我不知道为什么它没有为第二次测试生成新用户或从数据库中删除它。有什么想法吗?

1 个答案:

答案 0 :(得分:15)

在您的用户工厂中,请尝试以下方法:

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

为什么必须包含在卷曲括号中:避免缓存值

  

运行factory(:user)块   定义工厂时,而不是每次创建记录时。所以   如果Factory::Internet.email第一次评估为foo@bar.com,   然后工厂会尝试创建所有后续用户   那个电子邮件!)(根据@kristinalim,编辑语法)