3

我正在尝试编写一个规范来测试我的 user_login API,但是401在我运行规范时不断收到 JSON 电子邮件/密码不正确的错误。我正在执行以下操作:

require 'spec_helper'

describe User do
  subject(:user) do
    Program.create!(name: 'test', gender: 'Female', goal_id: '1', experience_id: '1')
    User.create!(email: 'test@test.com', password: '12345678', password_confirmation: '12345678', goal_id: '1', experience_level_id: '1', gender: 'Female')
  end

  it "is logged in" do
    post "/api/v1/login", user_login: {email: 'test@test.com', password: '12345678' }
    response.status.should be(201)
  end
end

有任何想法吗?

编辑 1

这是我的 session_controller,当用户通过 API 登录时正在使用它。

class Api::V1::SessionsController < Devise::SessionsController
    before_filter :authenticate_user!, except: [:create, :destroy]
    before_filter :ensure_params_exist
    skip_before_filter :verify_authenticity_token

  def create
    resource = User.find_for_database_authentication(email: params[:user_login][:email])
    return invalid_login_attempt unless resource

    if resource.valid_password?(params[:user_login][:password])
        sign_in("user", resource)
        resource.ensure_authentication_token!
        render 'api/v1/sessions/new.json.jbuilder', status: 201
        return
    end
    invalid_login_attempt
  end

  def destroy
        current_user.reset_authentication_token
        render json: {success: true}
  end

  protected

  def ensure_params_exist
    return unless params[:user_login].blank?
    render json: {success: false, message: "missing user_login parameter"}, status: 422
  end

  def invalid_login_attempt
    render 'api/v1/sessions/invalid.json.jbuilder', status: 401
  end
end
4

1 回答 1

1

我非常接近,也许这就是我遇到这么多麻烦的原因。这是我最终做的事情:

require 'spec_helper'

describe "sessions" do
  before do
    FactoryGirl.create(:program)
    @user = FactoryGirl.create(:user)
  end

  describe "user" do
    it "is logged in" do
  post "/api/v1/login", user_login: {email: @user.email, password: @user.password }

      response.status.should be(201)
    end
  end
end

我将块切换subjectbefore块,并将实例变量用于电子邮件和密码。就是这样!

于 2013-10-09T18:32:55.877 回答