Forum: RSpec Testing Views with Authentication

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
6d465bb8df6bda89904c7aafea0dda6c?d=identicon&s=25 Donald French (Guest)
on 2008-10-09 01:32
(Received via mailing list)
I am trying to figure out how to properly test a view when part of the
view is is protected with a role check <% if current_user.admin? %>..
How do I force a log in or mock the current user. I need to do it in a
DRY way as this is used throughout the system checking various
privileges.

Don French
5d38ab152e1e3e219512a9859fcd93af?d=identicon&s=25 David Chelimsky (Guest)
on 2008-10-09 02:01
(Received via mailing list)
On Wed, Oct 8, 2008 at 6:31 PM, Donald French <dhf0820@gmail.com> wrote:
> I am trying to figure out how to properly test a view when part of the view
> is is protected with a role check <% if current_user.admin? %>..  How do I
> force a log in or mock the current user. I need to do it in a DRY way as
> this is used throughout the system checking various privileges.

View examples are decoupled from controllers, so logging in won't do
anything. What you want to do is stub the current user, like this:

  template.stub!(:current_user).and_return(mock_model(User, :admin? =>
true)

In terms of keeping things DRY, there are a couple of things you can
do. First, you can simplify things by adding a helper in
application_helper.rb:

  def admin?
    current_user.admin?
  end

Now there's less to stub in the view examples.

This could also be a block helper:

  def admin_only
    yield if block_given? && current_user.admin?
  end

That lets you write this in your views:

  <% admin_only do %>
    ... super privileged stuff ...
  <% end %>

And this in the code examples that you want to yield:

  template.stub!(:admin_only).and_yield

And this in the code examples that you don't want to yield:

  template.stub!(:admin_only)

Now if ALL of your examples should render the admin-only stuff, you
could do this:

Spec::Runner.configure do |config|
  config.before(:each, :type => :view) do
    template.stub!(:admin_only).and_yield
  end
end

However, this means that all the view examples will be doing this
IMPLICITLY and is likely to cause some confusion down the road (why
the hell is this admin-only stuff getting rendered?), so that risk
needs to be taken into account.

HTH,
David
42172acdf3c6046f84d644cb0b94642c?d=identicon&s=25 Pat Maddox (pergesu)
on 2008-10-09 02:22
(Received via mailing list)
Donald French <dhf0820@gmail.com> writes:

> http://rubyforge.org/mailman/listinfo/rspec-users
You can stub the template object:
  template.stub!(:current_user).and_return mock_admin

Pat
This topic is locked and can not be replied to.