Testing a helper with a block
I’ve been doing a lot of Rspec testing lately. Although I’ve been using it for a while to do BDD I realize that I have not been testing things as well as I should. Yesterday I was trying to add tests for a helper method that ensures the passed in block is only output if the user is logged in and an administrator. It’s a fairly simple helper method.
def admin_accessible(&block)
if logged_in? and current_user.admin
concat(capture(&block), block.binding)
end
end
I stumbled in the test though as I was unsure of how to test a helper that accepts a block. With the help of my colleague we came up with the following two solutions to this problem.
describe ApplicationHelper, 'invoke admin_accessible helper, when logged in as admin' do
before(:each) do
@user = mock("user")
@user.stub!(:admin).and_return(true)
self.stub!(:logged_in?).and_return(true)
@block = "Testing admin_accessible"
end
# Solution 1
it 'shall return captured block' do
html = eval_erb <<-ERB
<% admin_accessible do %>
<div><%= @block %></div>
<% end %>
ERB
html.should have_tag('div', @block)
end
# Solution 2
it 'shall return captured block' do
_erbout = ""
html = admin_accessible do
_erbout << "<div>#{@block}</div>"
end
html.should have_tag('div', @block)
end
end
Do you know of a better solution?
More of my rantings
- Google Maps API with large data sets
- Stubbing controller methods in a helper test
- Creating a Backyard
These might also interest you
- Goodbye WebFaction Django Hosting – A Reflection (Aware Labs)
- 100 free websites worth $100,000 (No Pun Intended)
- Cable Decluttering With a Twist (Tomas Carrillo)