FactoryGirl, рельсы, огурцы: объединить несколько записей - PullRequest
0 голосов
/ 02 марта 2012

ОК, страницы factoryGirl в thinkbot очень полезны, но я делаю что-то не так. На более ранней итерации базовой функции я сделал две записи и принудительно установил связь в соответствии с сокращенным примером ниже:

 Given /^a price for corn has already been entered$/ do
   corn = Commodity.create!(name: "Corn", wholesale_unit: "ton")
   Price.create!(commodity: corn, retail_high: "19")
 end

Теперь я хочу сделать две цены, чтобы я мог проверить среднее значение по огурцу, чтобы убедиться, что оба тянутся. Я легко создал фабрики для вышеупомянутого согласно предложению Нэша.

 FactoryGirl.define do
   factory :commodity do 
     name 'Corn'
     wholesale_unit 'ton'
   end

   factory :price do 
     sequence(:retail_high) { |n| '19#{n}' }
     commodity
   end
 end

В моем обновленном файле step.rb я пытаюсь создать условия, которые работают на первой итерации, но имеют две записи:

 Given /^there are prices entered$/ do 
   Factory(:commodity)
   Factory(:price) do
     sequence(:retail_high)
   end
 end

Так что моя настоящая проблема в том, что я не могу добраться до первой базы, потому что когда я использую pry, чтобы увидеть, создается ли запись, я получаю Price = nil. То же самое с товаром. Есть так много атрибутов, что заводская работа действительно поможет. Обновление приведенных ниже примеров Nash показывает правильную первую запись, но вторая запись является повторением первой. Ниже приведены моя модель, соответствующий контроллер и схема. Спасибо за повешение, Сэм

commodity.rb:

 class Commodity < ActiveRecord::Base
   has_many :prices
 end

price.rb:

 class Price < ActiveRecord::Base
   belongs_to :commodity
 end

commodities_controller.rb:

  class CommoditiesController < ApplicationController
    def show
    @commodity = Commodity.find(params[:id])
   end

соответствующая схема.rb:

   create_table "commodities", :force => true do |t|
   t.string   "name"
   t.datetime "created_at"
   t.datetime "updated_at"
   t.string   "wholesale_unit"
   t.string   "retail_unit"
   t.string   "farm_gate_unit"
   t.string   "delivered_unit"
   t.string   "receipt_unit"
     end

  create_table "prices", :force => true do |t|
   t.date     "date"
   t.string   "price_type"
   t.string   "quality"
   t.string   "farm_gate_unit"
   t.decimal  "farm_gate_high"
   t.decimal  "farm_gate_low"
   t.string   "delivered_unit"
   t.decimal  "delivered_high"
   t.decimal  "delivered_low"
   t.string   "wholesale_unit"
   t.decimal  "wholesale_high"
   t.decimal  "wholesale_low"
   t.string   "retail_unit"
   t.decimal  "retail_high"
   t.decimal  "retail_low"
   t.datetime "created_at"
   t.datetime "updated_at"
   t.integer  "commodity_id"
 end

1 Ответ

1 голос
/ 03 марта 2012

Я предполагаю, что вы используете FactoryGirl 2.

# factories.rb

FactoryGirl.define do
  factory :commodity do
    name 'Corn'
    wholesale_unit 'ton'
  end

  factory :price do
    retail_high { Random.new.rand(100..500) }
    commodity
  end
end

# steps.rb

Given /^there are prices entered$/ do 
  FactoryGirl.create_list(:price, 2, commodity: Factory(:commodity))   
end

Это даст вам два ценовых объекта для одного и того же товара кукурузы.Если вы хотите сфабриковать две цены на разные товары, вы можете написать:

Given /^there are prices entered$/ do 
  Factory(:price) # this for corn   
  Factory(:price, commodity: Factory(:commodity, name: 'Weat'))
end
...