【问题标题】:wrong response status in rspec + devise + factory_girlrspec + devise + factory_girl 中的错误响应状态
【发布时间】:2016-10-13 19:55:12
【问题描述】:

所以我一直在尝试进行基本的响应测试 - 使用 200 和 403。我不确定我是否需要添加任何其他内容 ..

accounts_spec.rb

RSpec.describe Api::V1::AccountsController, :type => :controller do
  describe "GET index no account" do
    it "has a 403 status code" do
      get :index
      expect(response.status).to eq(403)
    end
  end
  describe "GET index with account" do
    login_user
    it "has a 200 status code" do
      get :index
      expect(response.status).to eq(200)
    end
  end
end

帐户控制器#index

def index
    #show user details
    raise if not current_user
    render json: { :user => current_user.as_json(:except=>[:created_at, :updated_at, :authorization_token, :provider, :uid, :id])}
    rescue
    render nothing: true, status: 403   
end

我不断得到

1)Api::V1::AccountsController GET index with account has a 200 status code
expected: 200
got: 403

有什么想法我做错了吗?

更新

module ControllerMacros
  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      user = FactoryGirl.create(:user)
      sign_in :user, user
    end
  end
end

【问题讨论】:

  • 尝试用 begin 块包裹 raise。所以开始...raise...渲染json:{:user ...救援什么都不渲染:true,状态:403结束
  • 这种包装也不起作用...

标签: ruby-on-rails ruby rspec devise factory-bot


【解决方案1】:

更简洁的实现

class SomeController < ApplicationController

  before_action :authenticate
  skip_before_action :verify_authenticity_token, if: :json_request?

  def index
    render json: { user: current_user...
  end

protected
  def json_request?
    request.format.json?
  end

  def authenticate
    head :unauthorized unless current_user
  end
end

我还建议使用 ActiveModel 序列化器https://github.com/rails-api/active_model_serializers。这将分离渲染 json 的逻辑,并且 oy 在序列化器下将有一个单独的类,用于定义 json 输出。所以你的渲染方法看起来像这样:

render json: current_user, status: :ok

app/serializers/user.rb

class UserSerializer < ActiveModel::Serializer
  attribute :id, :email #list your attributes for json output
end

如果你想在你的 rspec 中测试 json 响应,我发现最好的方法是针对这个库 https://github.com/sharethrough/json-schema-rspec 这样的 json 模式进行测试。

希望对你有帮助

【讨论】:

  • 谢谢你的重构,我不知道这样写是可能的......但这并不能回答我的要求。错误依然存在
  • 您的 rspec 中是否包含设计助手? RSpec.configure 做 |config| config.include Devise::TestHelpers, :type => :controller end
  • 请填写您在测试中使用的 login_user。唯一的原因是会话不是从 rspec 设置的。工厂女孩就像 user = FactoryGirl.create(:user) ....user.confirm!..sign_in user
  • 已更新。虽然我不知道user.confirm在哪里!应该是
  • 在创建用户之后如果你在sign_in之前使用可确认模块:用户,用户,所以创建用户,确认签名。另一种方法是在 Factory Girl 中设置 confirm_at
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
相关资源
最近更新 更多