【问题标题】:factory_girl's Cucumber steps and optional associationsfactory_girl 的 Cucumber 步骤和可选关联
【发布时间】:2011-01-23 19:22:33
【问题描述】:

我有以下型号:

class Person < ActiveRecord::Base
  belongs_to :family
end

class Family < ActiveRecord::Base
end

还有以下工厂:

Factory.define :person do |p|
  p.association :family
end

Factory.define :family do |f|
end

我正在使用 factory_girl 的 Cucumber 步骤,如下所示:

Given the following people exist:
  | First name | Last name |
  | John       | Doe       |

Given the following people exist:
  | First name | Last name | Family             |
  | John       | Doe       | Name: Doe's family |

我想使用第一种形式创建没有关联家庭的人,而后者则创建有家庭的人。现在每个人都有一个家庭。其实使用第一种形式是失败的,因为我在Family类中也有validates_presence_of :name

如果我从 Person 工厂定义中删除 p.association :family,后一种形式会失败,因为它试图将字符串设置为关联记录(它运行类似于 family = "Name: ..." 的东西)。

是否可以在 factory_girl 定义的 Cucumber 步骤中具有可选关联?

【问题讨论】:

    标签: ruby-on-rails cucumber factory-bot


    【解决方案1】:

    我会创建另一个工厂,例如:

    Factory.define :orphan, :class => "Person" do |factory|
      # does not belong to a family
    end
    

    然后在您的第一个设置中使用它:

    Given the following orphans exist:
      | First name | Last name |
      | John       | Doe       |
    

    【讨论】:

      【解决方案2】:

      我会让你的默认人员无关联,然后定义一个添加关联的子工厂,这可能有点违反直觉,但这是建立类层次结构的正确方法:

      Factory.define(:person) do |f|
      
      end
      
      Factory.define(:family_member, :parent => :person) do |f|
        f.association(:family)
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多