ruby-on-rails - 为什么我的工厂测试会引发另一家工厂的错误?

标签 ruby-on-rails rspec model devise factory-bot

我对 Rspec 和factory_bot 还很陌生。我有以下工厂:

FactoryBot.define do
  factory :user do
    email { "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a7b6a0a793b4beb2babffdb0bcbe" rel="noreferrer noopener nofollow">[email protected]</a>" }
    password { "azerty" }
    username { "test" }
    city { "Paris"}
  end

  factory :game do
    title { "Mega Man X" }
    nostalgia_point { 9 }
    platform { "Super Nintendo" }
    developer { "Capcom" }
    release_date { Date.new(1994,1,1) }
    game_mode { "Single player" }
    genre { ["Adventure", "Platform", "Shooter"] }
    association :owner, factory: :user
  end

  factory :favorite do
    user
    game
  end
end

当我运行此测试时:

require 'rails_helper'

RSpec.describe Game, type: :model do
  let!(:favorite) { create(:favorite) }

  describe '::create' do
    context 'persistence' do
      it 'persists the favorite' do
        expect(Favorite.count).to eq(1)
      end
    end
  end
end

我收到以下错误:ActiveRecord::RecordInvalid: 验证失败:电子邮件已被占用,用户名已被占用

我想这是因为我的用户工厂(设计模型)没有从我的其他测试中清除,但我绝对不确定......而且我不知道我是否应该使用不同的东西从我清理所有数据库所做的事情来看。这是我在 factory_bot.rb 中编写的内容:

RSpec.configure do |config|
  config.include Warden::Test::Helpers

  config.after :each do
    Warden.test_reset!
  end

  config.include FactoryBot::Syntax::Methods
end

如果有更好的做法或者只是告诉我我缺少什么,我将非常感激。谢谢!

最佳答案

您的用户模型中必须进行验证,以防止您使用数据库中已有的电子邮件和/或用户名创建用户。由于您有一个工厂(favorite),它尝试创建用户和游戏,而不首先检查用户电子邮件和/或用户名是否已存在,因此它会失败,因为它使用您设置的值对于他们来说,它们总是相同的(“[email protected] ”,“测试”,相应地)。

您可以使用 FactoryBot sequence为此:

sequence :email do |n|
  "test#{n}@gmail.com"
end
sequence :username do |n|
  "test-#{n}"
end

这会阻止您对新记录使用相同的值,因为 sequence 会生成增量整数,因此只要测试套件运行,该值就保证不会相同。

关于ruby-on-rails - 为什么我的工厂测试会引发另一家工厂的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68512761/

相关文章:

javascript - ERB Javascript 条件错误

rspec - 获取 Rspec 示例标签

ruby-on-rails - Rswag 和 Rspec : Undefined method for URL parameter

ruby-on-rails - 使用 Rails.cache 时 Rspec 测试失败,但如果我执行 binding.pry 则通过

java - 使用 Java 为现有模型制作动画?

ruby-on-rails - Rails 3 has_and_belongs_to_many 在 View 中创建复选框

ruby-on-rails - 如何处理 :reject_if if a new record and not an update

C++ 在结构中存储函数和运算符

json - 编写 SwiftUI 模型以使用数组读取 JSON 文件

ruby-on-rails - 在 Rails mail_to 帮助程序中使用变量作为主题参数