简体   繁体   English

RSpec 控制器规范:如何测试呈现的 JSON?

[英]RSpec controller spec: How to test rendered JSON?

I'm trying to test a simple controller's action of a Rails API我正在尝试测试 Rails API 的简单控制器操作

Here's the controller in question:这是有问题的控制器:

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

Here are my specs so far到目前为止,这是我的规格

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

I want to test the response.我想测试响应。 Something like in this Stack Overflow question How to check for a JSON response using RSpec?类似于 Stack Overflow 问题如何使用 RSpec 检查 JSON 响应? :

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

My problem is that response.body is an empty string.我的问题是response.body是一个空字符串。 Why is that ?这是为什么 ?

Not sure what kind of serializer you're using.不确定您使用的是哪种序列化程序。 But, render is not a method on an ActiveModel::Serializer .但是, render不是ActiveModel::Serializer上的方法。 Try this instead:试试这个:

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

If your TransactionSerializer is an ActiveModel::Serializer , Rails will, by convention, just use it to serialize each Transaction record in the ActiveRecord::Relation .如果您的TransactionSerializerActiveModel::Serializer ,按照惯例,Rails 将仅使用它来序列化ActiveRecord::Relation中的每个事务记录。

And, test it like this:并且,像这样测试它:

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

Part of the problem here might have been that you weren't actually calling get :index until after the tests ran.这里的部分问题可能是你没有实际调用get :index直到after的测试中跑出。 You need to call it before the tests run.您需要在测试运行之前调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM