加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:06:18 所属栏目:百科 来源:网络整理
导读:这是我的spec文件,当为上下文添加测试“而不是可单独更新用户余额”时,我得到以下错误. require 'spec_helper'describe Sale do context 'after_commit' do context 'assignable' do sale = FactoryGirl.create(:sale,earned_cents: 10,assignable: true) af
这是我的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,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!”:验证失败:已经收到电子邮件(ActiveRecord :: RecordInvalid)

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

解决方法

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

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

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

The factory(:user) block is run
when defining the factory,and not every time a record is created. So
if Factory::Internet.email evaluated to foo@bar.com the first time,then the factory would attempt to create all subsequent users with that very same email!) (as per @kristinalim,Edited for grammar)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读