Rails: Can I test for the presence of a button_to?

1.5k Views Asked by At

My site had dozens of instances of "link_to". I decided to change most of them to "button_to" for better appearance. The lines of my test that used to check for the presence of those links are no good anymore.

assert_select "a", :href => user_path(@seminar.teacher), text: "Your Teacher Profile", count: 2

The test doesn't work correctly with

assert_select "button", etc...

Is there a way to adjust the test to find the button_to instances? From my initial searches, it seems like there isn't.

I'm also considering simply cutting those lines from the tests, since I've read in another article that simply testing for the presence of display items isn't a very useful way to use rails tests.

Thanks in advance for any insight!

3

There are 3 best solutions below

3
kcdragon On BEST ANSWER

I would remove those tests that just test for the presence of a link. It would be better to write tests that click those buttons and test what happens after the button is clicked. Users care more about what happens when a button is clicked than the presence of a button on a page.

0
Steve Carey On

Here is one way to test for the presence of button_to using Rails' default testing framework MiniTest. In this example there is a button on a member's show page to change their membership status to inactive:

<%= button_to 'Change status to Inactive', membership_path(@membership), method: :patch, 
    params: { 'membership[status]' => 'Inactive'} %>

If you inspect your view in a web browser to see the HTML (in Chrome, right click the button element then select Inspect) you'll see that button_to is actually a form. So you can test for the existence of a form element with an action property equal to the specific membership_path.

membership = Membership.first
assert_select 'form[action=?]', membership_path(membership.id)

If you want to also test that the button's text is present then do a block

membership = Membership.first
assert_select 'form[action=?]', membership_path(membership.id) do
  assert_select 'input[value=?]', 'Change status to Inactive'
end
0
Carson Cole On

Updated for Rails 7, and likely 6, system tests.

assert_button "Click me"