使用rspec测试rails的嵌套属性

mai*_*ald 6 rspec ruby-on-rails

我对测试和rails非常陌生,并试图自己解决这个问题,但没有运气.

我有以下型号

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
Run Code Online (Sandbox Code Playgroud)

和一个相当标准的控制器,我猜......

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

我将如何进行测试呢?我试过这样的东西,但是我无法让它起作用:

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
Run Code Online (Sandbox Code Playgroud)

它可能与属性传递给create action的方式有关,但我怎样才能使它工作?我使用rails 3.1.rc5,但我怀疑这与它为什么不工作有任何关系......

或者你不会测试这个,因为它是基本的轨道功能,并且最有可能在开始时经过良好测试?

Ste*_*eve 6

尝试:

post :create, :product => Factory.attributes_for(:product, :pictures => [ Factory.build(:picture) ])
Run Code Online (Sandbox Code Playgroud)


jon*_*nii 5

正如你所说,你真的不需要对它进行测试,因为它将被基本的rails功能所覆盖,这样的东西应该由你的集成测试完全覆盖.

但是,如果您想要测试它,最好的方法是关闭您的开发日志并查看正在发布到操作的内容,将其复制并粘贴到您的测试中,然后根据您的需要进行修改.

不幸的是,使用属性或factory_girl属性不会削减它.