2011-08-12 153 views
5

嵌套属性,我是很新,测试和轨道,并试图找出自己,但没有任何运气。测试轨道使用RSpec

我有以下型号

class Picture < ActiveRecord::Base 
    belongs_to :product 
    has_attached_file :image 
end 

class Product < ActiveRecord::Base 
    has_many :pictures, :dependent => :destroy 
    accepts_nested_attributes_for :pictures, :reject_if => lambda { |p| p[:image].blank? }, :allow_destroy => true 
end 

和控制器,这是非常标准的,我猜...

def create 
    @product = Product.new(params[:product]) 
    if @product.save 
    redirect_to products_path, :notice => "blah." 
    else 
    render :action => "new" 
    end 
end 

我将如何去和测试呢?我想是这样的,但我不能得到它的工作:

describe ProductsController do 
    it "adds given pictures to the product" do 
    product = Factory.build(:product) 
    product.pictures.build(Factory.attributes_for(:picture)) 
    post :create, :product => product.attributes 
    Product.where(:name => product[:name]).first.pictures.count.should == 1 # or something 
    end 
end 

它可能有一些做的属性传递到创建行动的方式,但我怎么能得到这个工作?即时通讯使用rails 3.1.rc5,但我怀疑这与它为什么不工作有什么关系...

或者你会不会测试这一切,因为它是基本的rails功能,并且最有可能经过很好的测试?

回答

5

正如你说的,你并不真的需要测试这一点,必然的,因为它会由基本轨功能覆盖,而像这样的东西应该由你的集成测试进行彻底覆盖。

但是,如果你要测试的这款最好的办法就是尾部开发日志,查看被发布到行动,复制并粘贴到您的测试,然后修改它适合您的需求。

使用属性或属性factory_girl不会不幸削减它。

+0

我强烈同意这种看法。如果您没有测试,并且您没有任何规格说明和文档,则不会发生任何回归。 – phikes

+0

@phikes你看到我说测试使用集成测试它的一部分吗? – jonnii

5

尝试:

post :create, :product => Factory.attributes_for(:product, :pictures => [ Factory.build(:picture) ])