Reputation: 870
I have this Rails helper method that returns text with links inside it:
def add_to_library_event_text(event)
user_link = link_to(event.user.username, user_path(event.user))
game_link = link_to(event.game_purchase.game.name, game_path(event.game_purchase.game))
return user_link + " added " + game_link + " to their library."
end
What I want to do is write a spec for it, to make sure it outputs the right text. I don't care much about the exact details of the HTML, and I'd prefer to do this in a helper spec rather than a feature/browser spec since it's much faster.
I have a working test already, it looks like this:
expect(helper.add_to_library_event_text(add_to_library_event)).to eq \
"<a href=\"/users/#{user.username}\">#{user.username}</a> added <a href=\"/games/#{game.id}\">#{game.name}</a> to their library."
I'm hoping there's some way that I haven't found yet that will allow me to strip out the HTML from this, so I can write a comparison like this:
expect(helper.add_to_library_event_text(add_to_library_event)).to eq \
"#{user.username} added #{game.name} to their library."
Is there anything in RSpec/Rails that'd allow me to strip the HTML from this?
Upvotes: 2
Views: 1438
Reputation: 6227
When I want to match particular text within any complex markup (such as HTML), I like to use match
or include
, something like this:
expect(output).to include "#{user.username} added #{game.name} to their library."
or...
expect(output).to match /#{user.username} added #{game.name} to their library./
This cuts to the essence of what you're testing, and is very resilient to changes in markup, focusing on the content.
Upvotes: 0
Reputation: 870
I figured out how to do this! I use strip_tags
to strip the HTML from the input string.
expect(
strip_tags(helper.add_to_library_event_text(game_purchase_library_event))
).to eq "#{user.username} added #{game.name} to their library."
https://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-strip_tags
You could also use the sanitize(html_string_goes_here, tags: [])
method, but this is simpler as far as I can tell.
Upvotes: 1