doptimusprime
doptimusprime

Reputation: 9395

controller is Nil in rspec test

I have following RSpec test:

require 'rails_helper'
require 'spec_helper'

RSpec.describe "Users", type: :request do  


  describe "sign in/out" do

    describe "success" do
      it "should sign a user in and out" do
        attr = {:name=>"Test1",
        :email => "[email protected]",
        :password => "foobar",
        :password_confirmation => "foobar"
        }
        user = User.create(attr)
          visit signin_path
        fill_in "Email", :with => user.email
        fill_in "Password", :with => user.password
        puts page.body
        click_button "Sign in"
        controller.should be_signed_in
        click_link "Sign out"
        controller.should_not be_signed_in
      end
    end
  end

end

I am getting the following error:

 Failure/Error: controller.should be_signed_in
   expected  to respond to `signed_in?

This is because controller is nil. What is wrong here which causes controller to be nil?

Controller class is:

class SessionsController < ApplicationController
  def new
    @title = "Sign in"
  end
  def create
    user = User.authenticate(params[:session][:email],
                             params[:session][:password])
    if user.nil?
      flash.now[:error] = "Invalid email/password combination."
      @title = "Sign in"
      render 'new'
    else
      sign_in user
      redirect_to user
    end
  end
  def destroy
    sign_out
    redirect_to root_path
  end
end

signed_in method is defined in session helper which is included.

Ruby platform information: Ruby: 2.0.0p643 Rails: 4.2.1 RSpec: 3.2.2

Upvotes: 0

Views: 607

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84114

This is a request spec (which is basically a rails integration test) which is designed to span multiple requests, possibly across controllers.

The controller variable is set by the request methods that integration testing provides (get, put, post etc.)

If instead you use the capybara DSL (visit, click etc.) then the integration test methods never get called and accordingly controller will be nil. When using capybara you don't have access to individual controller instances so you can't test things such as what signed_in? returns - you have to test a higher level behaviour (e.g. what is on the page).

Upvotes: 4

Related Questions