RSpec and HAML Helpers
Today I faced a problem with specing a helper where I use the haml_tag/puts methods (haml_tag was previously open).
Here’s a solution working with Rails 2.0.2, RSpec 1.0.3 and HAML 1.8.2 :
in spec_helper.rb add :
Spec::Runner.configure do |config|
...
# Activate haml to spec helpers
config.with_options(:behaviour_type => :helpers) do |config|
config.include Haml::Helpers
config.include ActionView::Helpers
config.prepend_before :all do
# Update from Evgeny comment, with HAML >= 1.8.2, you can call
init_haml_helpers
# Old way for HAML <= 1.8.2
# @haml_is_haml = true
# @haml_stack = [Haml::Buffer.new]
end
end
...
end
then you can write your helper spec like this :
describe ApplicationHelper do
describe "#top_navigation_menu when logged in" do
it "returns the menu" do
@user = mock_model(User)
capture_haml {
top_navigation_menu(@user)
}.should_not be_empty
end
end
The interesting method is capture_haml, which does the same as Rails builtin capture but for HAML.
haml_tag/puts methods write output directly to the buffer and does not return the generated content as a String, thus we cannot just test on the method output.
Wed, 21 May 2008 21:35 Posted in Development Tools, Ruby, RubyOnRails
2 comments »
-
By Evgeny 23/05/2008 at 13h39
-
By Jonathan Tron 23/05/2008 at 14h15
Thanks Evgeny, I tried using #init_haml_helpers before but it never worked.
I tried one more time after your comment and it looks like I didn’t call it in the right place as it works now.
Great.
Instead of @haml_is_haml, in the new version (Haml > 1.8.2) the syntax will be just – #init_haml_helpers
So when using edge haml, there is a shortcut.
Strange how I wrote the same piece of code … a long time ago …
http://blog.kesor.net/2007/07/22/writing-helpers-with-haml-and-rspec/ and it didn’t really work.