1

我有一个页面呈现编辑评论表单。 一切在浏览器中按预期工作。现在试图为它编写一个集成测试,并且它以422状态失败。展望直通测试日志它的错误是:"ActionController::InvalidCrossOriginRequest: Security warning: an embedded <script> tag on another site requested protected JavaScript....Rails集成测试失败Ajax获取请求

不知道为什么我得到这个错误。我正在使用xhr: true, format: :js我所有的其他帖子/补丁ajax测试都按预期工作。

comments_test.rb:

require 'test_helper' 
class CommentsTest < ActionDispatch::IntegrationTest 
    def setup 
    @user = users(:user1) 
    @post = posts(:post1) 
    @comments = @post.comments 
    end 

    test "should get edit with ajax" do 
    log_in_as @user 
    get edit_comment_path(@comments.first), xhr: true, format: :js 
    assert_response 304 
    end 
end 

路线:

 user_post_comments POST /:user_id/:post_id/comments(.:format)  posts/comments#create 
    new_user_post_comment GET /:user_id/:post_id/comments/new(.:format) posts/comments#new 
      edit_comment GET /comments/:id/edit(.:format)    posts/comments#edit 
       comment PATCH /comments/:id(.:format)     posts/comments#update 
         PUT /comments/:id(.:format)     posts/comments#update 
         DELETE /comments/:id(.:format)     posts/comments#destroy 

comments_controller.rb:

class CommentsController < ApplicationController 
    before_action :authenticate_user! 
    before_action :set_comment, only:[:edit, :update, :destroy] 
    before_action :authorize_user, only:[:edit, :update, :destroy] 

    . 
    . 
    . 
    def edit 
    respond_to do |format| 
     format.html { render partial: "comments/form", locals: {commentable: @comment.commentable} } 
     format.js 
    end 
    end 
    . 
    . 
end 

edit.js.erb:

$("#comment_<%= @comment.hashid %>").hide(); 
$("#comment_<%= @comment.hashid %>").after('<%= j (render partial: "form", locals: { comment: @comment}) %>'); 

注:所有使用HTML格式正常工作。似乎是一个问题与csrf,但从我明白xhr: true, format: :js应该解决这个问题,和我所有的其他ajax测试工作正常。任何想法发生了什么?

回答

0

它按预期工作我我的测试更改为:

xhr :get, edit_comment_path(@comments.first), format: :js 
assert_response :success 

不知道为什么,当它适用于其他方法,如柱/补丁它不与xhr: true语法工作/删除.. 耸肩。