gpt4 book ai didi

ajax - 如何在 Rspec 中使用 Ajax 测试图像的移除

转载 作者:行者123 更新时间:2023-11-28 21:13:34 25 4
gpt4 key购买 nike

我在页面上有一张图片,我通过 Ajax 删除了它。

我想测试删除图片。

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

文件 destroy.js.erb - 刷新 View 并显示闪现消息

$('#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 删除图像 失败/错误:xhr :delete, :destroy, :id => @image.id 没有方法错误: 未定义的方法 images' for nil:NilClass
# ./app/controllers/images_controller.rb:32:in
破坏' # ./spec/controllers/images_controller_spec.rb:36:in block (4 levels) in <top (required)>'
# ./spec/controllers/images_controller_spec.rb:35:in
'

中的 block (3 级)

2) 已登录用户的 ImagesController 应该销毁图像 失败/错误:xhr :delete, :destroy, :format => "html" Action Controller ::路由错误: 没有路由匹配 {:format=>"html", :controller=>"images", :action=>"destroy"} # ./spec/controllers/images_controller_spec.rb:42:in `block (3 levels) in '

怎么了?

最佳答案

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

关于ajax - 如何在 Rspec 中使用 Ajax 测试图像的移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12164412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com