我可能在错误的方向上前进。我正在使用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
实现,因此应该在隔离环境中进行规格说明,但由于其被标记为受保护(似乎对于current_user
是一个成熟的模式),这使得编写规格说明变得更加困难......我将研究devise源代码。谢谢! - omadef current_#{mapping}
存在于lib/devise/controllers/helper.rb#self.define_helpers
中。没有独立的测试,只有通过 helpers 和assigns(:current_user)
进行测试。这样的通用代码难以浏览。我希望能够访问 helper_method,因为它是公共 API 的一部分。 - omasend
在这里需要的原因与helper_method
无关,仅仅是因为该方法受保护。 - Josh Dzielak