ruby-on-rails – RSpec和受保护的方法,current_user的控制器规范

我可能会这样做错了.我先做规格,BDD / TDD,碰撞.

我有这个application_controller_spec.rb

require "spec_helper"

describe ApplicationController do
  describe "current_user" do
    it "should return nil if no one is logged in" do
      subject.current_user.should be_nil
    end
    it "should return currently logged in user" do
      hash = {user_id: "my_id"}
      subject.should_receive(:session).and_return hash
      subject.current_user.should == "my_id"
    end
  end
end

没有受保护的关键字,它工作得很好.

application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery
  helper_method :current_user

  protected
  def current_user
    session[:user_id]
  end
end

与受保护启用,我得到这个错误msg

NoMethodError: protected method `current_user' called for #<ApplicationController:0x2a90888>

我应该能够使用helper_method来测试…任何建议?

解决方法

helper_method使得方法在视图中可用,而不是控制器,根据 the docs.

如果您真的需要访问控制器规范的方法,可以使用send:

subject.send(:current_user).should be_nil

但是,您可能想考虑测试非公开方法是否有意义,或者是否使用查看规范进行测试会更好.或者方法是否需要首先保护.看看Devise和Authlogic如何实现其current_user方法的测试也可能是有益的.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...