0

我在页面上有一个图像,我通过 Ajax 将其删除。

我想测试删除图像。

控制器:

def destroy

    current_image = Image.find(params[:id])
    current_car = current_image.car

    Image.delete_image_file(params[:id])    
    flash[:notice] = t('activerecord.errors.controllers.message.attributes.image.image_destroy_success')

    @images = current_car.images.order("order_id")

    respond_to do |format|
      format.html { redirect_to images_path(:car_id => params[:id]) }
      format.js
    end

  end

文件 destroy.js.erb - 刷新视图并显示 Flash 消息

$('#image_list').html("<%= escape_javascript(render('list')) %>")
$('#div_flash_box').html("<%= escape_javascript(render :partial => 'layouts/flash', :locals => { :flash => flash }).html_safe %>")

图像视图:_list.html.erb

<ul id="ul_images" data-update-url="<%= sort_images_url %>">  
  <% @images.each do |image| %>
    <%= content_tag_for :li, image, :class => 'ui-state-default' do %>     
     <%= link_to image_tag("#{RAILS_CAR_VIEW_IMAGES}" + "#{image.name}/" + image.image_thumb_file), "#{RAILS_CAR_VIEW_IMAGES}" + "#{image.name}/" + image.image_file, :class => 'group1' %>
     <div class="div-images-delete"><%= link_to t('views.buttons.delete'), image, :method => :delete, :remote => true, :confirm => t('views.forms.confirm') %></div>
    <% end %>
  <% end %>
</ul>

我在 Rspec 中的测试

it "should delete an image using Ajax" do
  lambda do
    xhr :delete, :destroy, :id => @image.id
    response.should be_success
  end.should change(Image, :count).by(-1)  
end



it "should destroy image" do
   xhr :delete, :destroy, :format => "html"
   flash[:notice].should == I18n.t('activerecord.errors.controllers.message.attributes.image.image_destroy_success')
end

汽车和图像有关系

class Image < ActiveRecord::Base
  belongs_to :car,
   :foreign_key => "car_id"

class Car < ActiveRecord::Base

  has_many :images

失败:

1) 登录用户的 ImagesController 应该使用 Ajax Failure/Error 删除图像:xhr :delete, :destroy, :id => @image.id NoMethodError: undefined method images' for nil:NilClass # ./app/controllers/images_controller.rb:32:indestroy' # ./spec/controllers/images_controller_spec.rb: 36:在block (4 levels) in <top (required)>' # ./spec/controllers/images_controller_spec.rb:35:in块(3级)中'

2) 登录用户的 ImagesController 应该销毁图像失败/错误:xhr :delete, :destroy, :format => "html" ActionController::RoutingError: No route matches {:format=>"html", :controller=> "images", :action=>"destroy"} # ./spec/controllers/images_controller_spec.rb:42:in `block (3 levels) in '

怎么了?

4

2 回答 2

1

第一个错误是因为您尝试删除的图像没有关联的汽车。听起来您在为此测试创建数据时忘记创建汽车。

另一个错误是因为您错过了id测试中的参数:

xhr :delete, :destroy, :format => "html"

应该

xhr :delete, :destroy, :id => @image.id, :format => "html"
于 2012-08-28T17:55:14.337 回答
1

对于第一个错误,我认为current_car测试环境中没有设置对象。这.images就是调用时出现 NilClass 错误的原因。

于 2012-08-28T17:43:34.123 回答