【问题标题】:in rails, when creating factorygirl for a model, shoudn't model's before_create be invoked?在rails中,为模型创建factorygirl时,不应该调用模型的before_create吗?
【发布时间】:2012-09-29 18:17:46
【问题描述】:

我的应用有一个 Phone 模型,其中一个字段是 .guid,它设置为 before_create :set_guid(它会生成一个随机字符串,并在创建模型时将其放入 guid 字段中)。

我的手机工厂如下:

require 'faker'

FactoryGirl.define do
  factory :phone do |f|
    f.phone { Faker::PhoneNumber.phone_number }
  end
end

这个创建手机的简单测试未能通过我的模型验证,因为 guid 为空白:

describe Phone do
  it "has a valid factory"  do
    FactoryGirl.create(:phone).should be_valid
  end

我当然可以手动填充 Factory 定义中的 guid 字段,但 Factory 的目的不是运行模型的正常验证和回调以确保它们正常工作吗?

显然我遗漏了一些东西 - 使用 FactoryGirl 创建模型实例的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails factory-bot


    【解决方案1】:

    你有一个带有 phone 属性的模型 Phone?

    除此之外,还有工厂女孩callbacks in their Getting Started

    
    factory :user do
      callback(:after_stub, :before_create) { do_something }
      after(:stub, :create) { do_something_else }
      before(:create, :custom) { do_a_third_thing }
    end
    

    类似 before(:create) 的方法可能对你有用。

    你不能在默认工厂中硬编码一个 guid 吗?我的意思是你只想测试一次看看它是否有效,然后剩下的只是镇流器,因为你想要工作测试。

    【讨论】:

    • 试过了,但无法弄清楚“do_a_third_thing”或者我是否还需要回调()...当我使用 before(:create) { f.set_guid } 时似乎什么也没发生。
    • 我实际上是在尝试使用工厂测试回调,以确保我的代码确实在创建正确的 guid。
    • 是的,我听到你的声音,有些日子很难用这样的东西。因此,当您忽略它并只执行 FactoryGirl.create(:phone) 时,您的 guid 仍然是空白的,对吧?
    • 感谢帮助...测试完全符合我的需要...我的验证实际上是错误的...我正在使用 before_create 设置我的 guid 并且应该一直这样做before_validation_on_create d'oh!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多