【问题标题】:Factory girl multiple values工厂女孩多重价值观
【发布时间】:2015-10-14 13:54:56
【问题描述】:

我知道我可以像这样给工厂女孩静态数据值:

  factory :post do
    title 'New post'
    number 7
  end

但是,如果我对每个标题和数字都有多个值怎么办。如果标题是 'New Post'、'Old Post'、'Hello' 并且号码是 7、8、9,我该如何将这些数据传递给工厂女孩?我应该使用数组还是使用多个 do 结束块?

【问题讨论】:

  • 为什么title会有3个值? 0o
  • @AndreyDeineko 这只是一个例子。您可以将标题替换为名称或其他任何内容。
  • 问题是一样的——为什么你会有一组(实际上,不止一个)属性的值? (元信息 - associations 救援)

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


【解决方案1】:
  1. 如果您想将值作为参数传递:

    factory :post do
      title 'Default Title'
    end
    
    # create(:post, title: 'Custom Title')
    
  2. 如果您只想随机化值,那么只需:

    factory :post do
      title {  ['New Post', 'Old Post', 'Hello'].sample }
    end
    

【讨论】:

    【解决方案2】:

    你可以这样做:

    posts_attrs = [{ title: 'new', number: 6}, { title: 'old' }]
    
    posts_attrs.each do |post_attrs|
      factory :post do
        title post_attrs[:title] || 'default title'
        number post_attrs[:number] || 1
      end
    end
    

    【讨论】:

      【解决方案3】:

      对于数字,您可以使用 FactoryGirl 序列:

      FactoryGirl.define do
        sequence :email do |n|
          "person#{n}@example.com"
        end
      end
      

      要生成一些随机字符串,有一个 gem Faker:

      FactoryGirl.define do
        factory :post do
          title { Faker::Lorem.sentence }
        end
      end
      

      Faker 可用于生成随机电子邮件、字符串、电子商务项目、地址和许多其他内容,请参阅 https://github.com/stympy/faker

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-18
        相关资源
        最近更新 更多