Rails,在返回 javascript 时测试 json 响应

Rails, Testing json response when javascript is also returned

我是 rails 的新手,目前正在尝试测试 return JavaScript 和 JSON 端点的响应作为响应。我的问题是我似乎只能查看 JavaScript 响应,而 returning 状态只会阻止 JavaScript 被执行。我到处都看过,但似乎找不到我当前问题的答案。 下面是我要测试的代码

respond_to do |format|
     if @comment.update(comment)
       format.json { render :news, status: :success, location: @comment }
       format.js   { }
     else
       format.json { render json: @comment.errors, status: :unprocessable_entity }
       format.js   { }
    end
end

我已经尝试 return 像下面这样的状态响应来测试状态,而不是阅读 JSON

head(422)

format.js { head :unprocessable_entity }

虽然这些似乎在获取响应方面起作用,但它们似乎也阻止了 JavaScript 的执行。 当试图断言正文的内容时,我似乎只能读取 JavaScript,JSON 似乎不存在。

 put update_comment_url(@comment), params: { comment: { uncensored: @comment.uncensored, id_reference: @comment.id_reference, page_type: @comment.page_type, replied_to: @comment.replied_to, user_id: @comment } }, xhr: true

当像下面这样明确请求某种格式时

put update_comment_url(@comment), params: { comment: { uncensored: @comment.uncensored, id_reference: @comment.id_reference, page_type: @comment.page_type, replied_to: @comment.replied_to, user_id: @comment },  :format => 'json'  }, xhr: true

这只会导致抛出错误,因为它希望出现一个不存在的视图。 我很可能误解了这里的一些概念,但我希望有人能指出正确的方向。

如果 rails 的任何新手都在寻找相同的答案,我已经在反复试验后找到了答案。像这样简单地将所需的格式放在括号中似乎对我有用。

put update_comment_url(@comment, format: :json), params: { comment: { uncensored: @comment.uncensored, id_reference: @comment.id_reference, page_type: @comment.page_type, replied_to: @comment.replied_to, user_id: @comment }}, xhr: true