vendredi 2 octobre 2015

Rspec Stub Application Controller Methods

I'm using omniauth at my rails app (4.2, ruby 2.2.1) and I defined this controller here:

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

I have no problem with those methods at my views, but my spec tests keep failing. I read that application controller's methods aren't available at the tests and then I tried to make them stubs.

Example of a failing test:

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

And the error:

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

And the method in a view:

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

Notes:

  • With or without the stub, the result is the same
  • The tests doesn't seem to complain about the current_user method, but I don't know if it's because they're failing when they find the logged_in? methods
  • I already checked some other questions here, but none of them helped me.
  • This way to stub also didn't helped me:

    allow(controller).to receive(:logged_in?).and_return(false)

Aucun commentaire:

Enregistrer un commentaire