1

編集コメントフォームをレンダリングしているページがあります。 すべては、意図したとおりにブラウザで動作します。今はそれのための統合テストを書こうとしていて、422のステータスで失敗しています。テストログを見れば、エラーは次のようになります。"ActionController::InvalidCrossOriginRequest: Security warning: an embedded <script> tag on another site requested protected JavaScript....ajax getリクエストでRails統合テストが失敗する

なぜこのエラーが発生するのか分かりません。私は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構文では動作しない理由は考えてすくめ.. 。

関連する問題