好的,thinkbot上的factoryGirl页面非常有用,但我做错了。在基本特征的早期迭代中,我创建了两个记录并按照下面的缩写示例强制关联:
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查看是否正在创建记录时,我得到的价格=零。与商品相同。有很多属性让工厂上班真的会有所帮助。将以上更新为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
相关的schema.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
答案 0 :(得分:1)
我假设你使用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