SilverNightaFall
SilverNightaFall

Reputation: 4170

NoMethodError undefined method `save' for nil:NilClass

What do I need to do to fix this? I am new to ruby on rails.

Error when rspec is ran

1) remember token should have a nonblank remember token
 Failure/Error: before { @user.save }
 NoMethodError:
   undefined method `save' for nil:NilClass
 # ./spec/models/user_spec.rb:125:in `block (2 levels) in <top (required)>'

user_spec.rb

require 'spec_helper'
describe User do

 before do
@user = User.new(name: "Example User", email: "[email protected]",
password: "foobar", password_confirmation: "foobar")
end
.
.
.
it { should respond_to(:remember_token) }
.
.  
.
describe "with a password that's too short" do
    before { @user.password = @user.password_confirmation = "a" * 5 }
    it { should be_invalid }
  end
  describe "return value of authenticate method" do
    before { @user.save }
    let(:found_user) { User.find_by_email(@user.email) }
    describe "with valid password" do
      it { should == found_user.authenticate(@user.password) }
    end
    describe "with invalid password" do
      let(:user_for_invalid_password) { found_user.authenticate("invalid") }
      it { should_not == user_for_invalid_password }
      specify { user_for_invalid_password.should be_false }
    end
  end
end
describe "remember token" do
  before { @user.save }
  it "should have a nonblank remember token" do
    subject.remember_token.should_not be_blank

  end
end

user.rb

class User < ActiveRecord::Base
      attr_accessible :name, :email, :password, :password_confirmation

      has_secure_password
      before_save { |user| user.email = email.downcase }
      before_save :create_remember_token

      validates :name, presence: true, length: { maximum: 50 }
      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
      validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
      uniqueness: { case_sensitive: false }
      validates :password, length: { minimum: 6 }
      validates :password_confirmation, presence: true

      private
      def create_remember_token
        self.remember_token = SecureRandom.urlsafe_base64
      end
    end

Upvotes: 0

Views: 3763

Answers (2)

Victor Hazbun Anuff
Victor Hazbun Anuff

Reputation: 196

the @user variable will be not found, so

you should move describe "remember token" inside ->

describe User do

  //current definitions

  describe "remember token" do
    before { @user.save }
     it "should have a nonblank remember token" do
       subject.remember_token.should_not be_blank
     end
  end
end

Upvotes: 0

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

It looks like this block of code

describe "remember token" do

is outside the block

describe User do
  ...
end

If you move it inside the block, then it will have the before action fire that creates the @user object (which you then save in your own before block)

Upvotes: 5

Related Questions