Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec assigns(:items).should eq([item]) returns nil

I'm very new to RSpec, and obviously doing something wrong.

Have basic controller with Index action:

class TransactionsController < ApplicationController

  before_filter :authenticate_user!
  def index
    @transactions = current_user.transactions
    respond_to do |format|
      format.html { render layout: "items" } # index.html.erb
      format.json { render json: @transactions }
    end
  end
end

And have a default RSpec test for Index action.

require 'spec_helper'

describe TransactionsController do
   describe "GET index" do
     it "assigns all transactions as @transactions" do
       transaction = FactoryGirl.create(:transaction)
       get :index
       assigns(:transactions).should eq([transaction])
     end
   end
end

So all works, except that the line assigns(:transactions).should eq([transaction]) returns nil, so I get this error:

Failure/Error: assigns(:transactions).should eq([transaction])

   expected: [#<Transaction id: 1, user_id: 1, text: "some transaction", date: "2013-02-02", money: #<BigDecimal:b8a8e90,'0.999E1',18(18)>, created_at: "2013-02-02 09:17:42", updated_at: "2013-02-02 09:17:42">]
        got: nil

   (compared using ==)
 # ./spec/controllers/transactions_controller_spec.rb:17:in `block (3 levels) in <top (required)>'

Would appreciate any tips, as I've spent all day on this.

like image 981
Serge Vinogradoff Avatar asked Dec 27 '22 10:12

Serge Vinogradoff


1 Answers

firstly, if you use before_filter :authenticate_user! you need to pass that filter.

this could be done by using sign_in some_user

secondly, when you are assigning the transactions @transactions = current_user.transactions

and you expect that there should be some in the spec, you will have to create transactions that are ASSIGNED TO THE CURRENT USER FactoryGirl.create(:transaction, user: some_user)

like image 114
phoet Avatar answered Dec 28 '22 22:12

phoet