Reputation: 17020
Consider, for example, the following code:
class ViewHelpersTest < ActionView::TestCase
should 'generate tag with correct parameters' do
assert_equal theme_stylesheet_link_tag('style', :media => 'print'),
'<link href="/themes/default/stylesheets/style.css" media="print" rel="stylesheet" type="text/css" />'
end
end
current_theme_stylesheet_tag
is a view helper that creates a stylesheet link tag that points to a css file located inside the current theme's directory. The current theme can be retrieved by calling ApplicationController::current_theme
.
So, I need to provide a valid controller instance, which brings me to my question:
How exactly do I specify the controller to be used when testing view helpers in Rails 3?
Also, if there is a better way to express this test, please let me know. I have little experience with testing.
Upvotes: 3
Views: 1377
Reputation: 47548
I'm not a big fan of testing helpers, but if you do it's best to approach it as a unit test, so you want to isolate the method from dependencies. In this case, instead of trying to create a controller object, you can just create a mock object and stub the necessary method call.
In RSpec this might work like so, assuming your current_theme
method just returns a string:
describe ViewHelper do
it "should generate tag with correct parameters" do
ApplicationController = double(:current_theme=>"A string")
helper.my_helper_method("argument").should == "A string"
end
end
When the helper method executes ApplicationController::current_theme
, it uses the stub instead of the actual method, so there's no need to instantiate a controller, or even to require the controller code.
Upvotes: 2
Reputation: 10763
I'm not the testing expert but I wonder if that should be a controller test instead of a view test. For example, Rails Guides describes view tests as "asserting the presence of key HTML elements and their content."
If you're setting the theme in the controller, can you test it there?
Upvotes: 0