On Wed, Oct 8, 2008 at 6:31 PM, Donald F. email@example.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? =>
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
Now there’s less to stub in the view examples.
This could also be a block helper:
yield if block_given? && current_user.admin?
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:
And this in the code examples that you don’t want to yield:
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
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.