Rails:如何检查使用“render json:”创建的响应?

Fli*_*lip 3 ajax json controller ruby-on-rails

我试图了解通过渲染 JSON 异步更新 Rails 视图的机制(因为我的老板希望这样做)。

到目前为止还不是很成功。

有没有办法检查操作系统层上看到的响应?就像我使用时一样curl?我正在尝试将我的学习成果写成一篇有关该主题的博客文章,并且有一种方法可以可视化 Rails 在渲染 JSON 时发出的内容,这将非常有帮助。

重要的控制器部分如下所示:

def create
  @order = Order.find_by(id: params[:order_id])
  @comment = current_user.comments.new(comment_params)
  .
  .
  return unless @comment.save!

  respond_to do |format|
    format.json { render json: @comment, context: self }
  end

end
Run Code Online (Sandbox Code Playgroud)

编辑:

根据我尝试使用调试器/撬来检查响应的评论之一,首先确保 @comment 对象包含数据:

(byebug) @comment
#<Comment id: 3090, order_id: 125, user_id: 18, content: "asdfad", created_at: "2017-02-01 12:21:25", updated_at: "2017-02-01 12:21:25">
Run Code Online (Sandbox Code Playgroud)

看起来不错。

(byebug) response.body
""
Run Code Online (Sandbox Code Playgroud)

不太酷,JSON 数据在哪里?为什么身体是空的?

Gen*_*sov 5

您可以编写测试来实现您的目标,也可以将代码放入after_action {puts response.body }控制器中。

应用程序控制器.rb

class ApplicationController < ActionController::Base
  ...
  after_action { puts response.body }
  ...
end
Run Code Online (Sandbox Code Playgroud)

一些_测试规范.rb

require 'rails_helper'

RSpec.describe YourController, type: :controller do

  describe "GET #index" do

    it "returns some data" do
      get :index

      puts response.body

      binding.pry # for interactive debugging

      expect(response.status).to eq(200)
    end

  end

end
Run Code Online (Sandbox Code Playgroud)