RSpec 控制器规格:如何测试渲染 JSON?

RSpec controller spec: How to test rendered JSON?

我正在尝试测试 Rails API

的简单控制器操作

这是有问题的控制器:

class Api::TransactionsController < ApplicationController
  def index
    transactions = Transaction.all
    json = TransactionSerializer.render(transactions)
    render json: json
  end
end

这是我目前的规格

require 'rails_helper'

RSpec.describe Api::TransactionsController do
  describe '.index' do
    context "when there's no transactions in the database" do
      let(:serialized_data) { [].to_json }

      before { allow(TransactionSerializer).to receive(:render).with([]).and_return(serialized_data) }
      after { get :index }

      specify { expect(TransactionSerializer).to receive(:render).with([]) }
      specify { expect(response).to have_http_status(200) }
    end
  end
end

我想测试响应。类似于这个 Stack Overflow 问题 How to check for a JSON response using RSpec?:

specify { expect(response.body).to eq([].to_json) }

我的问题是 response.body 是一个空字符串。这是为什么 ?

不确定您使用的是哪种序列化程序。但是,render 不是 ActiveModel::Serializer 上的方法。试试这个:

module Api
  class TransactionsController < ApplicationController
    def index
      transactions = Transaction.all
      render json: transactions
    end
  end
end

如果您的 TransactionSerializer 是一个 ActiveModel::Serializer,Rails 将按照惯例只使用它来序列化 [=16= 中的每个 T运行saction 记录].

然后,像这样测试它:

require 'rails_helper'

describe Api::TransactionsController do
  describe '#index' do
    context "when there's no transactions in the database" do
      let(:transactions) { Transaction.none }

      before do
        allow(Transaction).to receive(:all).and_return(transactions)

        get :index
      end

      specify { expect(response).to have_http_status(200) }
      specify { expect(JSON.parse(response.body)).to eq([]) }
    end
  end
end

这里的部分问题可能是您实际上并没有调用 get :index,直到 after 测试 运行。您需要在测试前调用它 运行.