How to escape an interpolated string in an Xpath in Rspec/Nokogiri?

I have the following line in a feature spec and it’s failing when a user has a single quote in their name:

find(:xpath, "//tr[contains(.,#{@family.last_name})]/td/a", text: "Sign In As").click

Works fine for OConnell but fails with O’Connell:

Failure/Error: find(:xpath, "//tr[contains(.,#{@family.last_name})]/td/a", text: "Sign In As").click
       Invalid expression: //tr[contains(.,O'Connell)]/td/a

It’s like the single quote is terminating the expression but I’m using double quotes throughout. Or is it because it’s opening a string that’s never closed in the expression?

I’ve tried figuring out how to escape the single quote but I can’t even get it working with a hardcoded string, let alone an interpolated one.

Yeah, nested escaped quotes can be confusing. I think this should work:


which would cause the regxp itself to be processed as:


which after interpolation would look be:

1 Like

@andyw8 you diamond! Works like a charm :smile: