NoMethodError未定义的方法`save'代表nil:NilClass

时间:2012-06-04 18:56:09

标签: ruby-on-rails rspec

我需要做些什么来解决这个问题?我是新来的ruby on rails。

运行rspec时出错

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: "user@example.com",
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

2 个答案:

答案 0 :(得分:5)

看起来像这段代码

describe "remember token" do

在区块之外

describe User do
  ...
end

如果你在块中移动它,那么它会有一个before action fire,它会创建@user对象(然后你会在块之前保存在你自己的对象中)

答案 1 :(得分:0)

找不到@user变量,所以

你应该在里面描述“记住令牌” - &gt;

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