我可能会走错路。我先做规范,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
效果很好没有
protected
关键词。application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
protected
def current_user
session[:user_id]
end
end
与
protected
启用,我收到此错误消息NoMethodError: protected method `current_user' called for #<ApplicationController:0x2a90888>
我应该能够使用 helper_method 进行测试...有什么建议吗?
最佳答案
helper_method
根据the docs,使该方法在 View 中可用,而不是在 Controller 中可用。 .
如果您确实需要从 Controller 规范中访问该方法,您可以使用 send
:
subject.send(:current_user).should be_nil
但是您可能需要考虑测试非公共(public)方法是否有意义,或者使用 View 规范进行测试是否更好。或者是否首先需要保护该方法。看看 Devise 和 Authlogic 如何为他们的
current_user
实现测试可能也很有启发性。方法。
关于ruby-on-rails - RSpec 和 protected 方法,current_user 的 Controller 规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5195065/