Testing Views with Authentication

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 F.

On Wed, Oct 8, 2008 at 6:31 PM, Donald F. [email protected] 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

Donald F. [email protected] writes:

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

Pat