ruby-on-rails – 使用rspec测试rails的嵌套属性

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 使用rspec测试rails的嵌套属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对测试和rails非常陌生,并试图自己解决这个问题,但没有运气.

我有以下型号

  1. class Picture < ActiveRecord::Base
  2. belongs_to :product
  3. has_attached_file :image
  4. end
  5.  
  6. class Product < ActiveRecord::Base
  7. has_many :pictures,:dependent => :destroy
  8. accepts_nested_attributes_for :pictures,:reject_if => lambda { |p| p[:image].blank? },:allow_destroy => true
  9. end

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

  1. def create
  2. @product = Product.new(params[:product])
  3. if @product.save
  4. redirect_to products_path,:notice => "blah."
  5. else
  6. render :action => "new"
  7. end
  8. end

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

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

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

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

解决方法

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

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

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

猜你在找的Ruby相关文章