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

问题描述 投票:0回答:1

我是Rails的新手,目前正尝试测试返回JavaScript和JSON作为响应的端点的响应。我的问题是,我似乎只能查看JavaScript响应,而返回状态只是阻止了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

我尝试返回如下所示的状态响应以测试状态,而不是读取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

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

javascript ruby-on-rails json integration-testing minitest
1个回答
0
投票

[如果有人不熟悉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
© www.soinside.com 2019 - 2024. All rights reserved.