Search code examples
ruby-on-railsrubycapybararuby-test

How to use regexp in assert_selector ruby on rails


I have a selector that displays date and time on the page, need to write capybara test to check for just date. How to include regexp in assert_selector?

assert_selector("div", text: /"#{DateTime.now.strftime('%a %b %d, %H:%M')}"*/i)

It doesn't work as a regular expression. What's the syntax in order to test for partial text or substring using assert_selector in ruby on rails


Solution

  • The text option does accept a regex to match against text, but it also defaults to partial matching so passing a regex is not normally necessary

    assert_selector("div", text: DateTime.now.strftime('%a %b %d, %H:%M'))
    

    will do a partial match against the text of the elements.

    If you really want to use a regex (assuming you didn't actually mean to check for surrounding "s) then you'd want something like

    assert_selector("div", text: /#{Regexp.escape(DateTime.now.strftime('%a %b %d, %H:%M'))}/i)