0

我需要做什么来解决这个问题?我是 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

用户.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
4

2 回答 2

5

看起来像这段代码

describe "remember token" do

在街区外

describe User do
  ...
end

如果您将其移动到块内,那么它将具有创建 @user 对象的 before 操作触发(然后您将其保存在您自己的 before 块中)

于 2012-06-04T19:00:46.600 回答
0

将找不到 @user 变量,因此

你应该在里面移动描述“记住令牌”->

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
于 2012-06-04T21:08:43.670 回答