Using webrat contains a (text) match with haml
I am using the following webrat delimiter:
response.should contain(text)
With the following haml:
%p You have = current_user.credits credits
I wrote a cucumber step "Then I should see" You have 10 credits "which uses a webrat match. The step fails, webrat does not find any text in the response because the haml actually creates
<p>You have
10
credits</p>
How can I get a match for the output of the output that haml produces?
Note: the above is a simplified example of the situation I am dealing with. Writing the following haml is not an acceptable solution:
%p= "You have #{current_user.credits} credits"
source to share
You are right, this is pain. I found Webrat to be too annoying for a long time.
Two ideas:
- Correct your test. In this case, you want it to be blind to newlines, so get rid of them:
response.tr("\n","").should contain(text)
- Fix your Haml. This is probably the best option. You can use a multiline terminator
|
to tell Haml not to put line breaks in:
% p You have | = current_user.credits | credits
See Haml link for more obscure things like this. (A surprising amount that has to do with whitespace.)
source to share
I found something like:
response.should contain(/You have 10 credits/m)
often gives me the match I want without me to go with my humle. Given the choice between discarding my markup, which I really want to read, and changing my helper to a regex, the latter seems like a small price to pay to code the view more easily.
source to share
There are various possibilities in Haml for manipulating whitespace, but the right thing to do here is either reconsider the match, be whitespace free, or use a filter to write inline content. For example:
%p
:plain
You have #{current_user.credits} credits
Or, if you need more complex logic:
%p
:erb
You have <%= current_user.credits %> credits
Haml is designed to effectively express document structure, but it is not that good for expressing inline content. When you want to do fancy inline stuff (like here), it makes sense to go to ERB / ββHTML rather than just Haml judging. See this blog post for details .
source to share