V
V
Vasily Shakhunov2016-08-13 18:13:27
Ruby on Rails
Vasily Shakhunov, 2016-08-13 18:13:27

How to test sessions_controller?

There is a sessions_controller that creates a session based on the model with has_secure_password

class SessionsController < ApplicationController
  layout 'signin'

  def create
    user = User.find_by_email(params[:sessions][:email])
    if user && user.authenticate(params[:sessions][:password])
      session[:user_id] = user.id
      redirect_to user_tasks_path(user), notice: 'Вы вошли в систему.'
    else
      flash[:alert] = 'Неверные почта или пароль'
      render :new
    end
  end

end

I'm trying to do some testing. Idea taken from here .
RSpec.describe SessionsController, type: :controller do

  describe '#create' do
    let(:user_params) do
      {email: Faker::Internet.email, password: 'password'}
    end

    let(:user) { FactoryGirl.create(:user, user_params) }

    it 'created user should exist' do
      db_user = User.find_by_email(user.email)
      expect(db_user.email).to eq(user.email)
    end

    context 'with valid params' do

      before :each do
        post :create, { sessions: user_params }
      end

      it 'should redirect to user tasks' do
        expect(response).to render_template(:index)
      end

      it 'flash message should be good' do
        expect(flash[:notice]).to eq 'Вы вошли в систему.'
      end

      it 'should authenticate user' do
        expect(session[:user_id]).to eq(user.id)
      end
    end
...

Accordingly, the tests fail:
308a47459b574e3b9b09ffd58970be74.png
I understand that after "post: create, { sessions: user_params }" authentication does not occur. What could be the problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Shakhunov, 2016-08-15
@inf

The correct answer is to pass the variable in expanded form))

let(:user) { FactoryGirl.create(:user, user_params) }

    context 'with valid params' do

      before :each do
        post :create, sessions: {email: user.email, password: user.password }
      end

E
Evgeny Kungurov, 2016-08-15
@evgenykungurov

Use the capybara gem, testing is easier there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question