[Rails] Unit testing + instance variables
Jeremy Kemper
jeremy at bitsweat.net
Wed Mar 9 09:17:21 GMT 2005
Belorion wrote:
> After *much* digging and playing around, I finally figured out how to
> unit test instance variables that are created by actions. It was
> more difficult than I expected. It seems like there should have been
> a more straight forward way to do this. Can someone enlighten me? A
> simplified and somewhat contrived example of what I am current doing:
>
> def test_list
> get :list
> # This step seems exessively complex, and took me a while to figure out
> my_inst_vars = @controller.instance_variable_get "@assigns"
>
> assert_equal( 5, my_inst_vars["recipes"].size )
> assert_equal( 8, my_inst_vars["categories"].size )
> end
> end
These assertions test instance variables passed to the view from the
controller:
assert_template_has
assert_template_has_no
assert_assigned_equals
See http://manuals.rubyonrails.com/read/chapter/28#page78
However, they don't allow you to manipulate the instance variables. You
can pull them directly from the response instead:
def test_list
assert_equal 5, @response.template.assigns['recipes'].size
assert_equal 8, @response.template.assigns['categories'].size
end
Test::Unit::TestCase#assigns would be a convenient enhancement.
def test_list
assert_equal 5, assigns(:recipes).size
assert_equal 8, assigns(:categories).size
end
protected
def assigns(name)
@response.template.assigns[name.to_s]
end
jeremy
More information about the Rails
mailing list