【问题标题】:`raise_record_invalid` using FactoryBot with Rspec in Rails`raise_record_invalid` 在 Rails 中使用带有 Rspec 的 FactoryBot
【发布时间】:2018-03-09 19:16:07
【问题描述】:

我正在使用 FactoryBot 为我的 Rspec 测试创建假数据。我的用户工厂如下:

FactoryBot.define do
  factory :user do
    sequence(:name) { |n| "User#{n}" }
    sequence(:email) { |n| "user#{n}@email.com" }
  end
end

创建用户会在我的 User 模型中自动创建客户端作为后续操作:

def initialize_client
  self.client = self.build_client
  self.client.setup_stripe
  self.save
end 

我有一个客户工厂:

FactoryBot.define do
  factory :client do
    user
  end
end

我创建了一个 Rspec 文件来测试 client 在创建用户时是否正确构建:

describe User, type: :model do
  user = FactoryBot.create(:user)
end

但这会引发错误:

raise_record_invalid': Validation failed: Email has already been taken (ActiveRecord::RecordInvalid)

即使运行 FactoryBot.create(:user) 会创建已接受的客户端和用户。我不确定此时我需要更改什么

【问题讨论】:

  • 只是个疯狂的想法。 1. 杀死你的服务器 2. 运行 rails db:setup 3. 运行 rails db:setup RAILS_ENV=test
  • @KickButtowski 只是尝试这样做,没有帮助:/
  • 即使这个 rails db:setup RAILS_ENV=test?
  • @KickButtowski 好的,我刚刚用RAILS_ENV 尝试过,它可以工作。不过这很奇怪,如果您可以添加它,我会接受它作为答案。你介意解释我为什么要这样做吗?泰
  • 为您发布答案。希望我的解释足以让您开始。

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


【解决方案1】:

为了我的辩护,我对 FactoryBot 的经验并不丰富。

您在user = FactoryBot.create(:user) 中使用了create,它将在您的数据库中创建记录,因此当您尝试创建相同的记录时,您会收到错误消息。

  1. Read this for getting more info
  2. check this too

执行以下操作

  1. 杀死你的服务器,这样你就不会遇到有人在使用你的数据库
  2. 运行rails db:setup
  3. 运行rails db:setup RAILS_ENV=test

注意:全部

rails 数据库:设置

版本将帮助您重置数据库并运行您的种子文件(如果有)。

希望我的解释对您开始研究和了解更多信息有所帮助;)

【讨论】:

  • 你把我推向了正确的方向,对于任何偶然发现这篇文章的人,我最终将database_cleaner 添加到我的规范测试中,这样每次运行测试时都会清理交易
【解决方案2】:

我知道这个问题很老,但我喜欢使用不同的解决方案,也就是 Faker gem 的 Faker::Internet 部分。

FactoryBot.define do
  factory :user do
    name { Faker::Name.name }
    email { Faker::Internet.safe_email(name: name) }
  end
end
2.5.7 :013 > user = FactoryBot.build(:user)
 => #<User:0x00007fb93a19f690 @name="Warner Hayes", @email="warner.hayes@example.net">
2.5.7 :014 > user = FactoryBot.build(:user)
 => #<User:0x00007fb938ddadf8 @name="Basil Smitham", @email="smitham_basil@example.com">
2.5.7 :015 > user = FactoryBot.build(:user)
 => #<User:0x00007fb938de16a8 @name="Mr. Winfred Daugherty", @email="daugherty.mr.winfred@example.com">
2.5.7 :016 > user = FactoryBot.build(:user)
 => #<User:0x00007fb939bd2168 @name="Elodia Bartell PhD", @email="bartell.elodia.phd@example.com">
2.5.7 :017 >

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 2023-02-02
    相关资源
    最近更新 更多