简体   繁体   English

在 rspec 中设计重定向而不是 json 响应

[英]devise redirects instead of json response in rspec

I had overridden default responding in devise which renders json instead of html template.我在设计中覆盖了默认响应,它呈现 json 而不是 html 模板。 It works fine when I test it with curl or postman, but when it comes to test it with rspec.当我用 curl 或 postman 测试它时它工作正常,但是当我用 rspec 测试它时。 I have read infos how to test controllers with devise from readme.md, so that it works fine with logging into, but does not work when I want to test unauthenticated request.我已经阅读了有关如何使用 readme.md 中的设计测试控制器的信息,以便它可以正常登录,但在我想测试未经身份验证的请求时不起作用。

Response received:收到回复:

<html><body>You are being <a href=\"http://test.host/users/sign_in\">redirected</a>.</body></html>

instead of:代替:

{"error":"You need to sign in or sign up before continuing."}

app/controllers/playlists_controller.rb:应用程序/控制器/播放列表_controller.rb:

class PlaylistsController < ApplicationController
  before_action :authenticate_user!

  def index
    render json: Playlist.all
  end
end

app/controllers/sessions_controller.rb:应用程序/控制器/sessions_controller.rb:

class SessionsController < Devise::SessionsController
  clear_respond_to
  respond_to :json
end

spec/controllers/playlists_controller_spec.rb:规格/控制器/playlists_controller_spec.rb:

require 'rails_helper'

describe PlaylistsController do
  context 'when user is not signed in' do
    it 'returns authorization error message' do
      get :index
      expect(response.body).to eq 'some message here'
    end
  end
end

spec/support/devise.rb规格/支持/devise.rb

RSpec.configure do |config|
  config.include Devise::TestHelpers, type: :controller
end

In Rails 5, the only way I could get the controller action to process as JSON was :在 Rails 5 中,我可以让控制器操作作为 JSON 处理的唯一方法是:

get :action, params: { format: :json, ... }

Hope this can help !希望这可以帮助!

您可以定义FailureApp或使用条件过滤器,两者都在类似问题的答案中提出: https : //stackoverflow.com/a/10042104/580346

The reason it doesn't work in your controller test and does work in curl is because you aren't hitting the :index with format of :json (which you've written logic to respond_to :json ).它在您的控制器测试中不起作用并且在 curl 中起作用的原因是因为您没有使用:json格式访问:index (您已将逻辑写入respond_to :json )。

Change this改变这个

it 'returns authorization error message' do
  get :index
  ...
end

to this对此

it 'returns authorization error message' do
  get :index, format: :json
  ...
end

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

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