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

I am very new to RSpec and obviously something is wrong.

Has a base 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 check the 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 everything 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)>' 

Thank you for any advice as I spent all day on this.

+4
source share
2 answers

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

this can be done using sign_in some_user

secondly, when you assign transactions @transactions = current_user.transactions

and you expect that there should be something in the specification, you will have to create transactions that are assigned ONLY to the FactoryGirl.create(:transaction, user: some_user)

+10
source

Can you check if get: index works for controller.index? If yes, you need to check the routes

0
source

All Articles