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
     Nokogiri::XML::XPath::SyntaxError:
       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:

"//tr[contains(.,\"#{@family.last_name\"})]/td/a"

which would cause the regxp itself to be processed as:

//tr[contains(.,"#{@family.last_name"})]/td/

which after interpolation would look be:

//tr[contains(.,"O'Connell")]/td/
1 Like

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