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.
1
2
3
4
5
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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?
Need web application development, maintenance for your existing app, or a third party code review?
Velocity Labs can help.
Hire us!