加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:35:51 所属栏目:百科 来源:网络整理
导读:我可能会这样做错了.我先做规格,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.sh
我可能会这样做错了.我先做规格,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方法的测试也可能是有益的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读