Rails ajax 获取请求的集成测试失败

Rails integration test failing on ajax get request

我有一个正在呈现编辑评论表单的页面。 在浏览器中一切正常。现在尝试为它编写集成测试,但它失败了,状态为 422。查看测试日志,错误是:"ActionController::InvalidCrossOriginRequest: Security warning: an embedded <script> tag on another site requested protected JavaScript....

不确定为什么会出现此错误。我正在使用 xhr: true, format: :js 我的所有其他 post/patch 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 测试都可以正常工作。知道发生了什么事吗?

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

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

不知道为什么它不适用于 xhr: true 语法,而它适用于其他方法,例如 post/patch/delete.. shrug.