0

我在我的rails应用程序(4.2,ruby 2.2.1)中使用omniauth,我在这里定义了这个控制器:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  helper_method :current_user, :logged_in?

  def logged_in?
    !!current_user 
  end

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id] #memoized
  end
end

在我看来,这些方法没有问题,但我的规范测试一直失败。我读到应用程序控制器的方法在测试中不可用,然后我试图让它们成为存根。

失败测试示例:

require 'rails_helper'

RSpec.describe "docs/edit", type: :view do
  before(:each) do
    @doc = assign(:doc, create(:doc))
  end

  it "renders the edit doc form" do

    allow_any_instance_of(ApplicationController).to receive(:logged_in?).and_return(false)

    render

    assert_select "form[action=?][method=?]", doc_path(@doc), "post" do
    end
  end
end

和错误:

  1) docs/edit renders the edit doc form
     Failure/Error: render
     ActionView::Template::Error:
       undefined method `logged_in?' for #<#<Class:0x007fb1fab057d0>:0x007fb200ac6750>

以及视图中的方法:

<% if logged_in? %>
  <%= link_to t('your docs'), docs_path(author: current_user) %>
<% end %>

笔记:

  • 有或没有存根,结果是一样的
  • 测试似乎没有抱怨 current_user 方法,但我不知道是不是因为他们在找到 login_in 时失败了?方法
  • 我已经在这里检查了其他一些问题,但没有一个对我有帮助。
  • 这种存根的方式也没有帮助我:

    允许(控制器)。接收(:logged_in?)。and_return(假)

4

0 回答 0