mycellius
mycellius

Reputation: 598

Rails: unable to use a Regex in assert_select block

I want to check each link contained within my navigation against a regex. I've checked this same navigation for various links before using code like this:

assert_select "nav.active" do |nav|
  assert_select nav, "a[href=?]", edit_post_path(post), count: 0
end

Which works great. I'm unable to do something similar using a regex, as seen in the docs. I've tried using these variations (both of them commented out on purpose):

assert_select "nav.active" do |nav|
  #assert_select "a[href=?]", /.+/
  #assert_select nav, "a[href=?]", /foo/, count: 1
end

Which fails and outputs this:

Minitest::Assertion:  Expected exactly 1 element matching "a[href=/.+/]", found 0..

or

Minitest::Assertion:  Expected exactly 1 element matching "a[href=/foo/]", found 0..

What am I doing wrong?

Upvotes: 1

Views: 1044

Answers (1)

Heather V.
Heather V.

Reputation: 160

I came across this question today while looking for a similar answer. I just used this line successfully in my test:

assert_select "input:match('value',?)", /Clear search:/, count: 0

So the following should work.

#assert_select "a[href=?]", /.+/
assert_select "a:match('href',?)", /.+/

#assert_select nav, "a[href=?]", /foo/, count: 1
assert_select "a:match('href',?)", /foo/, count: 1

Rails 5 uses Nokogirl's implementation of assert_select. Based on its documentation, I don't think you need a reference to nav in the loop. https://github.com/kaspth/rails-dom-testing/blob/master/lib/rails/dom/testing/assertions/selector_assertions.rb

Upvotes: 5

Related Questions