RSpec测试失败找到用户

时间:2012-06-21 08:59:04

标签: ruby-on-rails ruby-on-rails-3 rspec

我的控制器(用户控制器)

 def reset_password
      @user = User.find_by_reset_code(params[:reset_code]) unless params[:reset_code].nil?     

      if request.post?    
        if @user && @user.update_attributes(:password => params[:user][:password], :password_confirmation => params[:user][:password_confirmation])
          self.current_user = @user
          @user.delete_reset_code
          flash[:success] = t('helpers.password_reset_successful')
          render :template => "sessions/new"
        else
          flash[:error] = t('helpers.password_reset_error')
          redirect_to root_path
        end
      end
   end

我想测试它,我做...

   it "POST 'reset password with reset code page'" do
        @user.reset_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )

        User.should_receive(:find_by_reset_code).with(@user.reset_code)
        post :reset_password, :user => {"id" => @user.id}
      end

但我在Rspec中有例外 -

Failure/Error: User.should_receive(:find_by_reset_code).with(@user.reset_code)
       (<User(id: integer, name: string, email: string, encrypted_password: string, salt: string, created_at: datetime, updated_at: datetime, admin: boolean, reset_code: string) (class)>).find_by_reset_code("acd8a322d9554fbde375f5c39446276188a41678")
           expected: 1 time
           received: 0 times

怎么了?

1 个答案:

答案 0 :(得分:2)

您的请求中没有reset_code个参数。

替换为:

post :reset_password, :reset_code => @user.reset_code

而你宁愿这样做:

User.should_receive(:find_by_reset_code).with(@user.reset_code).and_return @user