我有一个呈现编辑评论表单的页面。 一切都在浏览器中按预期工作。现在尝试为它编写集成测试,它失败了422状态。通过测试记录它的错误是:"ActionController::InvalidCrossOriginRequest: Security warning: an embedded <script> tag on another site requested protected JavaScript....
不确定我为什么会收到此错误。我正在使用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 :(得分:0)
按预期工作我将测试更改为:
xhr :get, edit_comment_path(@comments.first), format: :js
assert_response :success
当它适用于其他方法(例如post / patch / delete)时,不知道为什么它不能使用xhr: true
语法。耸肩。