我有一个页面正在呈现编辑评论表单。一切都会在浏览器中正常运行。现在尝试为其编写集成测试,但测试失败,状态为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 ..耸肩)时,为什么它不与语法一起工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句