Capybara matcher fails in view spec if data attribute contains quoted JSON

27 views
Skip to first unread message

Tasos Latsas

unread,
Jan 23, 2021, 4:43:54 PM1/23/21
to Capybara
Hi!

I am not really sure if this is a bug, or I am missing something, but as the subject suggest, when a data attribute includes JSON with quoted values, capybara matcher have_selector fails to match the element. If there are no quotes it works.

This is the script to reproduce the issue: https://gist.github.com/tlatsas/04c5f12656eb92d1c444b00aca3ce28f

Any idea what is happening here?

Thanks,
Tasos


Thomas Walpole

unread,
Jan 23, 2021, 7:30:23 PM1/23/21
to Capybara
Tasos, 
 I don't have time to dive deep into this right now, but it's most likely to be CSS escaping issues. Either way this isn't a great way to expect json in attributes since you're making your tests fully depending on the formatting of the json rather than the actual contents (an extra space in the json "text":<extra space>"value" for instance which wouldn't actually affect the json value.  A better approach would be to use a custom filter block to check the actual json value

expect(rendered).to have_selector('div#main') do |node|
  JSON.parse(node['data-quotes']) == {'text' => 'Text with "quotes"' }
end

Tasos Latsas

unread,
Jan 24, 2021, 5:43:15 AM1/24/21
to Capybara
Hi Thomas,

I switched from have_selector to RSpec's include, but your solution is way better so I will use a filter block.

Thank you.
Reply all
Reply to author
Forward
0 new messages