【问题标题】:devise redirects instead of json response in rspec在 rspec 中设计重定向而不是 json 响应
【发布时间】:2016-09-10 19:02:48
【问题描述】:

我在呈现 json 而不是 html 模板的设计中覆盖了默认响应。当我用 curl 或 postman 测试它时它工作得很好,但是当它用 rspec 测试它时。我已经阅读了如何使用 readme.md 中的设计测试控制器的信息,因此它可以在登录时正常工作,但在我想测试未经身份验证的请求时不起作用。

收到的回复:

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

代替:

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

app/controllers/playlists_controller.rb:

class PlaylistsController < ApplicationController
  before_action :authenticate_user!

  def index
    render json: Playlist.all
  end
end

app/controllers/sessions_controller.rb:

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

spec/controllers/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

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

【问题讨论】:

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


    【解决方案1】:

    在 Rails 5 中,我可以让控制器操作作为 JSON 处理的唯一方法是:

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

    希望这能有所帮助!

    【讨论】:

      【解决方案2】:

      它在您的控制器测试中不起作用并且在 curl 中起作用的原因是因为您没有使用格式为 :json:index(您已将逻辑写入 respond_to :json)。

      改变这个

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

      到这里

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

      【讨论】:

      • 那行得通。我想知道为什么这适用于 curl 而无需设置 Content-Type 或 Accept 标头而 rspec 不是...
      • 有趣。我假设您在 curl 中使用了内容类型 json。我其实不知道为什么它会在没有设置内容类型的情况下使用 json
      • 实际上没有设置标题。默认情况下它应该响应 json,因为它应该在被覆盖的控制器中。无论如何-感谢您回答我:)
      【解决方案3】:

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

      【讨论】:

      • 很好,这是为测试添加额外的逻辑。我已经使用 curl 进行了此操作,但是测试失败了。我认为我不应该仅为测试更改应用代码。
      • 你是对的,我错过了它与 curl 一起工作并且在测试中失败。顺便说一句,您可能会喜欢这篇文章的格式和标题:blog.iempire.ru/2016/09/05/rails-obstractions
      猜你喜欢
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-20
      • 2015-12-09
      相关资源
      最近更新 更多