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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – RSpec和受保护的方法,current_user的控制器规范前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可能会这样做错了.我先做规格,BDD / TDD,碰撞.

我有这个application_controller_spec.rb

@H_403_4@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

@H_403_4@class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user protected def current_user session[:user_id] end end

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

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

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

解决方法

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

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

@H_403_4@subject.send(:current_user).should be_nil

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

猜你在找的Ruby相关文章