I have an images on the page, which I removed via Ajax.
I want to test deleting images.
Controller:
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
File destroy.js.erb - Refreshing view and showing flash message
$('#image_list').html("<%= escape_javascript(render('list')) %>")
$('#div_flash_box').html("<%= escape_javascript(render :partial => 'layouts/flash', :locals => { :flash => flash }).html_safe %>")
View of images: _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>
My tests in 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
Cars and Images are in relationships
class Image < ActiveRecord::Base
belongs_to :car,
:foreign_key => "car_id"
class Car < ActiveRecord::Base
has_many :images
Failures:
1) ImagesController for signed-in users should delete an image using Ajax
Failure/Error: xhr :delete, :destroy, :id => @image.id
NoMethodError:
undefined method images' for nil:NilClass
# ./app/controllers/images_controller.rb:32:in
destroy'
# ./spec/controllers/images_controller_spec.rb:36:in block (4 levels) in <top (required)>'
# ./spec/controllers/images_controller_spec.rb:35:in
block (3 levels) in '
2) ImagesController for signed-in users should destroy image Failure/Error: 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 '
What's wrong?