Quick tip - assert_toggled
Recently I've been working on a project that requires testing many actions that simply toggle an attribute. This is especially common with admin tasks. An example would be providing an admin with the ability to close or unclose a ticket.
There are quite a number of assert_difference test helpers floating around out there (see reference section at the bottom for links) which I've always found useful. Here is an offshoot to be used for these boolean actions:
assert_toggled
def assert_toggled(object, method, difference=true)
initial_value = object.send(method)
yield
object.reload if object.respond_to? :reload
assert_equal (difference ? !initial_value : initial_value), object.send(method)
end
def assert_not_toggled(object, method, &block)
assert_toggled object, method, false, &block
end
Example usage
def test_close_as_admin
login_as :admin
assert_toggled(ticket, :closed?) do
post :close, :id => ticket.id
end
end
def test_close_as_non_admin
login_as :normal_user
assert_not_toggled(ticket, :closed?) do
post :close, :id => ticket.id
end
end
Reference


1 Comment
please delete the previous comment (i accidentaly) pushed the return key :)
Very useful tip anyway :) I'm thinking about an Rspec integration..
Commenting is closed for this article.