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

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
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 に答える