【问题标题】:RSpec and FactoryGirl - building unique assocations?RSpec 和 Factory Girl - 建立独特的关联?
【发布时间】:2013-12-29 20:33:33
【问题描述】:

feedback 模型需要account 才能存在。每个account 都有一个唯一的:uuid,在模型中验证:validates :uuid, presence: true, uniqueness: true

我正在使用 rspec 测试反馈模型,并且每当我构建 feedback 对象时不断收到 Uuid has already been taken 错误,因为反馈正在构建关联的 account

spec/models/feedback_spec.rb

require "spec_helper"

describe Feedback do
  it "is valid with a message" do
    expect(build(:feedback)).to be_valid
  end

  it "is invalid without a message" do
    expect(build(:feedback, message: nil)).to have(1).errors_on(:message)
  end

  it "is invalid without an associated account" do
    expect(build(:feedback, account: nil)).to have(1).errors_on(:account)
  end
end

spec/factories/feedbacks.rb

FactoryGirl.define do
  factory :feedback do
    association :account
    message Faker::Lorem.paragraphs
  end
end

spec/factories/accounts.rb

FactoryGirl.define do
  factory :account do
    # uuid SecureRandom.uuid # THIS LINE WILL NOT WORK
    sequence(:uuid) { |n| n } # THIS LINE WORKS
    active true
  end
end

从 accounts.rb 工厂可以看出,当我在 feedback_spec.rb 文件中创建 account 时,uuid SecureRandom.uuid 行似乎总是返回相同的 UUID。

我想知道,FactoryGirl 是否只构建一次帐户对象,然后为每个单独的测试重新使用它?我期待每个帐户对象都有一个唯一的 UUID,但这显然行不通。但是,当我切换到使用 sequence(:uuid) { |n| n } 行时,它工作得很好。

试图了解 FactoryGirl 如何创建这些对象进行测试。这显然不是我想的那样。我的测试现在可以正常运行,但我不明白的事情最终会回来困扰我。

【问题讨论】:

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


    【解决方案1】:

    试试这个:

    FactoryGirl.define do
      factory :account do
        uuid { SecureRandom.uuid }
        active true
      end
    end
    

    这将在调用帐户工厂时评估 SecureRandom.uuid,而不是仅在 FactoryGirl 定义其工厂时评估一次。

    编辑:

    请参阅Factory Girl Lazy Attributes 了解更多信息。

    【讨论】:

    • 我在重新阅读 RSpec 的一章后才发现。那些小花括号很狡猾!正如你所说,这确实解决了问题。
    • 被 Rspec 咬了又懒加载了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 2012-06-12
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多