如何编写请求规范来测试用户登录?

时间:2013-10-02 20:04:04

标签: ruby-on-rails rspec

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

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

这是我的sessions_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

1 个答案:

答案 0 :(得分: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

我将subject块切换为before块,并使用实例变量作为电子邮件和密码。就是这样!