如何在Rspec中测试使用Ajax删除图像
我在页面上有一个图像,我通过Ajax删除了它 我想测试删除图像 控制器:如何在Rspec中测试使用Ajax删除图像,ajax,ruby-on-rails-3,testing,rspec,Ajax,Ruby On Rails 3,Testing,Rspec,我在页面上有一个图像,我通过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
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 %>")
汽车和图像是相互关联的
class Image < ActiveRecord::Base
belongs_to :car,
:foreign_key => "car_id"
class Car < ActiveRecord::Base
has_many :images
类映像“汽车id”
类Car
失败:
1) 用于登录用户的ImagesController应使用Ajax删除图像
失败/错误:xhr:delete,:destroy,:id=>@image.id
命名错误:
nil:NilClass的未定义方法images'
#./app/controllers/images\u controller.rb:32:in
destroy'
#./spec/controllers/images\u controller\u spec.rb:36:in块(4级)in'
#./spec/controllers/images\u controller\u spec.rb:35:in
块(3层)in'
2) 已登录用户的ImagesController应销毁图像
失败/错误:xhr:delete,:destroy,:format=>“html”
ActionController::路由错误:
没有路由匹配{:格式=>“html”,:控制器=>“图像”,:操作=>“销毁”}
#./spec/controllers/images\u controller\u spec.rb:42:in'block(3层)in'
出什么问题了?对于第一个错误,我认为
当前\u car
对象未在测试环境中设置。这就是调用.images
时出现NilClass错误的原因。第一个错误是因为您试图删除的图像没有关联的汽车。这听起来像是您在为该测试创建数据时忘记创建汽车
另一个错误是因为您在测试中错过了id
参数:
xhr :delete, :destroy, :format => "html"
应该是
xhr :delete, :destroy, :id => @image.id, :format => "html"
你想做什么样的测试?控制器还是集成?还有,你得到了什么错误?我想检查控制器,但我应该测试什么?那很好。我看到了xhr,我还以为你在测试ajax视图。谢谢你,但是。。。失败/错误:xhr:delete,:destroy,:id=>@image.id,:format=>“html”NoMethodError:nil的未定义方法“images”:NilClass@user1466717这与您在第一次测试中遇到的错误相同,这是因为测试数据库没有很好地填充。该图像没有关联的汽车。
xhr :delete, :destroy, :format => "html"
xhr :delete, :destroy, :id => @image.id, :format => "html"