RSpec和受保护的方法,current_user的控制器规范

oma*_*oma 13 rspec ruby-on-rails

我可能会以错误的方式走这条路.我首先做的是规格,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
Run Code Online (Sandbox Code Playgroud)

这工作完全正常没有protected关键字.

application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery
  helper_method :current_user

  protected
  def current_user
    session[:user_id]
  end
end
Run Code Online (Sandbox Code Playgroud)

protected启用,我得到这个错误味精

NoMethodError: protected method `current_user' called for #<ApplicationController:0x2a90888>
Run Code Online (Sandbox Code Playgroud)

我应该可以使用helper_method进行测试......有什么建议吗?

zet*_*tic 13

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

如果您确实需要从控制器规范访问该方法,您可以使用send:

subject.send(:current_user).should be_nil
Run Code Online (Sandbox Code Playgroud)

但您可能想要考虑测试非公共方法是否有意义,或者是否更好地使用视图规范进行测试.或者首先是否需要保护该方法.看看Devise和Authlogic如何为他们的current_user方法实施测试也可能是有益的.