rails testing helpers with instance variable?
I want to test a helper where I use a instance variable inside. I'm using rails 2.3 with the default testing framework. Can please someone write my a simple test (I guess a Unit test) for this? thanks
A simpler version of my code as example.
# controller
@bla = "some value"
# view
<%= foo %>
开发者_如何学编程# helper
def foo
@bla.reverse
end
or is it a better practice to write this helper with a parameter call?
def foo(s)
s.reverse
end
You can test helpers quite easily and it's built into the test framework, so i'm not sure what jasonpgignac is saying.
Under test/unit/helpers you will see all of your helpers generated by your script/generate scaffold or controller... however you generate them.
Inside said file, you can just assert that a value is equal, because you are just testing to make sure the result is coming up how you expect. Here's one i pulled from my code:
require 'test_helper'
class PaymentsHelperTest < ActionView::TestCase
test "displays Month names" do
assert_equal "April 2010", month_and_year_name(payment_transactions(:one))
end
end
It's been awhile since i wrote this, but you call the actual helper in your assertion. In this case my helper was called month_and_year_name and i passed a fixture to it.
Easy stuff, that comes with the greatest testing framework known to man, test::unit and fixtures... as god intended.
Perhaps I'm missing something, but in the example you gave, you pretty much just wrote a one-to-one wrapper around the reverse function? What are you trying to do?
As for tests, there isn't a direct method to test helpers in the test suite that comes with rails, but there is a plugin that adds this functionality: http://nubyonrails.com/articles/test-your-helpers. I haven't used it in a while, but I think it still works.
精彩评论