maclover7
maclover7

Reputation: 137

RSpec undefined local variable or method

Having a weird error in spec/controllers/profiles_controller_spec.rb: undefined local variable or method 'profile'

Pasted in relevant sections of the controller:

require 'rails_helper'
require 'factory_girl'

describe ProfilesController, :type => :controller do
  login_user #this is defined elsewhere, not an issue
  describe "PUT update" do
    before(:each) do
      @profile = FactoryGirl.create(:profile)
    end
    context "valid attributes" do
      it "located the requested @profile" do
        put :update, id: @profile, profile: FactoryGirl.attributes_for(:profile)
        assigns(:profile).should eq(@profile)
      end
    end
  end
end

Upvotes: 0

Views: 4403

Answers (2)

spickermann
spickermann

Reputation: 106792

My guess is that there isn't a problem in your spec or your factory. The problem is with the controller you are testing.

The exception you see

1) ProfilesController PUT #update valid attributes located the requested @profile
   Failure/Error: put :update, id: @profile, profile: FactoryGirl.attributes_for(:profile)
   NameError:
     undefined local variable or method `profile' for #<ProfilesController:0x007fae343cfe08>

tells you that your ProfilesController has undefined local variable or method profile.

In your controller, you have this line

if @profile.update(profile)

that most likely causes the error. Perhaps you need need to change that update(profile) to update(profile_params)? This is hard to tell without seeing the whole controller, but that would follow a common pattern. And I guess you have a method profile_params that returns the filtered params.

Upvotes: 1

Luke Wright
Luke Wright

Reputation: 1

Have you defined a factory in test/factories.rb or spec/factories.rb?

It'll look something like this:

# This will guess the User class
FactoryGirl.define do
  factory :user do
    first_name "John"
    last_name  "Doe"
    admin false
  end

  # This will use the User class (Admin would have been guessed)
  factory :admin, class: User do
    first_name "Admin"
    last_name  "User"
    admin      true
  end
end

taken directly from the docs

Upvotes: 0

Related Questions