【发布时间】: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