Jump to content

The ultimate community for Ruby on Rails developers.


Photo

controller spec assigns method returns nil

rspec controller assigns

  • Please log in to reply
2 replies to this topic

#1 NerdcoreSteve

NerdcoreSteve

    Signalman

  • Members
  • 25 posts

Posted 22 June 2014 - 07:51 PM

Here's mah codes:

  1 require 'spec_helper'
  2
  3 describe PeopleController do
  4   let(:user) { FactoryGirl.create(:user) }
  5   let(:person) { FactoryGirl.create(:person, user: user) }
  6   let(:non_user_person) { FactoryGirl.create(:person) }
  7
  8   describe "Get #index" do
  9     it "populates an array of all the people associated with the current user" do
 10       get :index
 11       puts assigns(:person) == nil
 12       assigns(:people).should eq([person])
 13     end
 14   end
 15 end

And Here's some of the error output:

................true
F

Failures:

  1) PeopleController Get #index populates an array of all the people associated with the current user
     Failure/Error: assigns(:people).should eq([person])
       
       expected: [#<Person id: 88, first_name: "Billy", last_name: "Bobob", description: "Master of all potatoes", category: "thlurps", created_at: "2014-06-22 19:46:51", updated_at: "2014-06-22 19:46:51", user_id: 178>]
            got: nil

Now my people controller does have a before action and my googling has indicated this might cause the get action to return nothing.

  2   before_action :set_person, only: [:show, :edit, :update, :destroy]

But removing this line does not make the test pass and I'm pretty sure that this populates the person I want to show, edit, etc, on the page in question.

 

Hrm....

 

Shouldn't this work? What am I missing?



#2 NerdcoreSteve

NerdcoreSteve

    Signalman

  • Members
  • 25 posts

Posted 22 June 2014 - 08:23 PM

Well now, application_controller.rb has this line:

before_action :authenticate_user!

I've not yet needed to authenticate in other tests though (namely my policy specs).



#3 NerdcoreSteve

NerdcoreSteve

    Signalman

  • Members
  • 25 posts

Posted 23 June 2014 - 05:49 PM   Best Answer

And here's how I got it to work :)

  1 require 'spec_helper'
  2 include Devise::TestHelpers
  3
  4 describe PeopleController do
  5   let(:user1) { FactoryGirl.create(:user) }
  6   let(:user1_person) { FactoryGirl.create(:person, user: user1) }
  7
  8   let(:user2) { FactoryGirl.create(:user, email: "dumbguy@professionalsteve.com") }
  9   let(:user2_person) { FactoryGirl.create(:person, user: user2) }
 10
 11   before{ sign_in user1 }
 12
 13   describe "Get #index" do
 14     it "populates an array of all the people associated with the current user" do
 15       get :index
 16       assigns(:people).should eq([user1_person])
 17     end
 18   end
 19 end

Woot!

 


  • Ohm likes this





Also tagged with one or more of these keywords: rspec, controller, assigns

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users