【问题标题】:How to validates JSON type in RSpec?如何验证 RSpec 中的 JSON 类型?
【发布时间】:2014-02-13 03:53:08
【问题描述】:

我想在 RSpec 中将我的响应类型验证为 JSON,但 respond_with_content_typeshoulda-matchers 中不再可用。

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

我正在使用:

  • 导轨 (4.0.2)
  • rspec-rails (2.14.1)
  • 应该匹配器 (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

任何提示都会对我有用。谢谢!

【问题讨论】:

    标签: ruby-on-rails rspec tdd


    【解决方案1】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多