如何在RSpec中验证JSON类型?

时间:2014-02-13 03:53:09

标签: ruby-on-rails rspec tdd

我想在RSpec中将我的响应类型验证为JSON,但respond_with_content_type中不再提供shoulda-matchers

参考:https://github.com/thoughtbot/shoulda-matchers/issues/252

我正在使用:

  • rails(4.0.2)
  • rspec-rails(2.14.1)
  • shoulda-matcher(2.5.0)

这是我的控制者:

class BrandsController < ApplicationController
  def create
    @brand = Brand.new(permitted_params)
    if @brand.save
      render :json => permitted_params, :status => 200
    else
      render :nothing => true, :status => 500
    end
  end

  private 
  def permitted_params
    params.require(:brand).permit(:name)
  end
end

这是我的规格:

require 'spec_helper'

describe BrandsController do
  describe 'POST create' do
    context 'with empty data' do
      before(:each) { post :create, brand: { name: '' } }
      it { should respond_with 500 }
    end
    context 'with invalid data' do
      before(:each) { post :create, brand: { name: '123' } }
      it { should respond_with 500 }
    end
    context 'with valid data' do
      before(:each) { post :create, brand: { name: 'somebrand' } }
      it { should respond_with 200 }
      # should respond with JSON type
    end
  end
end

任何提示对我来说都很棒。谢谢!

1 个答案:

答案 0 :(得分:3)

试试这个

expect(response.headers["Content-Type"]).to eql("application/json; charset=utf-8")