加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 23:28:30 所属栏目:百科 来源:网络整理
导读:我对测试和rails非常陌生,并试图自己解决这个问题,但没有运气. 我有以下型号 class Picture ActiveRecord::Base belongs_to :product has_attached_file :imageendclass Product ActiveRecord::Base has_many :pictures,:dependent = :destroy accepts_neste
我对测试和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

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

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,但我怀疑这与它为什么不工作有任何关系……

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

解决方法

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读