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

时间:2018-12-27 18:10:49

标签: ruby-on-rails ruby rspec rspec-rails

我正在尝试测试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

我要测试响应。此堆栈溢出问题How to check for a JSON response using RSpec?中的内容:

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

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

1 个答案:

答案 0 :(得分:1)

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

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

如果您的TransactionSerializerActiveModel::Serializer,按照惯例,Rails将使用它来序列化ActiveRecord::Relation中的每个Transaction记录。

然后,像这样测试它:

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测试运行。您需要在测试运行之前调用它。