【发布时间】:2018-02-02 18:08:05
【问题描述】:
我有一个呈现编辑评论表单的页面。 一切都按预期在浏览器中运行。现在尝试为它编写一个集成测试,它以 422 状态失败。通过测试日志查看错误是:"ActionController::InvalidCrossOriginRequest: Security warning: an embedded <script> tag on another site requested protected JavaScript....
不知道为什么我会收到此错误。我正在使用xhr: true, format: :js 我所有其他的 post/patch ajax 测试都按预期工作。
cmets_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
cmets_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 测试都可以正常工作。知道发生了什么吗?
【问题讨论】:
标签: javascript ruby-on-rails ajax integration-testing ruby-on-rails-4.2