ruby-on-rails - RSpec 和 protected 方法,current_user 的 Controller 规范

标签 ruby-on-rails rspec

我可能会走错路。我先做规范,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/

相关文章:

ruby-on-rails - Rails 不会从夏令时过渡出来

ruby-on-rails - GitHub 上的 Ruby on Rails 开源社交应用

ruby-on-rails - rails 路线和 Controller 参数

ruby-on-rails - 升级到 Rails 4 - 强大的参数

ruby-on-rails - Rspec:如何期望模拟在 `each` 循环中接收方法

ruby-on-rails - Rails open_uri 和 amazon s3 `open_http' : 403 Forbidden (OpenURI::HTTPError)

ruby-on-rails - 使用 RSpec 测试回形针文件上传

ruby-on-rails - 不需要的符号到哈希键的字符串转换

ruby-on-rails - 如何在 RSpec 中编写可重用的共享示例

ruby-on-rails - Rails 3 + Rspec : Testing that a model has an attribute?