使用rspec测试rails的嵌套属性

时间:2011-08-12 18:08:13

标签: ruby-on-rails 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

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

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

2 个答案:

答案 0 :(得分:6)

尝试:

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

答案 1 :(得分:5)

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

但是,如果你想测试这个,那么最好的方法是关闭你的开发日志,看看发布到操作的内容,将其复制并粘贴到你的测试中,然后根据你的需要进行修改。

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