rspec / rspec-rails

RSpec for Rails 6+
https://rspec.info
MIT License
5.16k stars 1.03k forks source link

aggregate_failures with assert_select #2482

Closed woto closed 3 years ago

woto commented 3 years ago

Hi! It seems that aggregate_failures doesn't work with assert_select? Or I am doing something wrong? *crosspost from google groups https://groups.google.com/g/rspec/c/4Xj5BatQyjk

Your environment

Steps to reproduce

aggregate_failures do
  expect(true).to eq(false)
  expect(true).to eq(nil)
end

returns

0.1) Failure/Error: expect(true).to eq(false)

            expected: false
                 got: true

            (compared using ==)

            Diff:
            @@ -1 +1 @@
            -false
            +true
          # ./spec/requests/tables/news_controller_spec.rb:63:in `block (5 levels) in <top (required)>'

     0.2) Failure/Error: expect(true).to eq(nil)

            expected: nil
                 got: true

            (compared using ==)
          # ./spec/requests/tables/news_controller_spec.rb:64:in `block (5 levels) in <top (required)>'

but

aggregate_failures do
  assert_select 'h1', 'Newss'
  assert_select 'h2', count: 4
end

returns only:

Minitest::Assertion: <Newss> expected but was
<News>..
Expected 0 to be >= 1.

  0) Tables::NewsController#index with follow_redirect! has correct title
     Failure/Error: assert_select 'h1', 'Newss'

     Minitest::Assertion:
       <Newss> expected but was
       <News>..
       Expected 0 to be >= 1.
     # ./spec/requests/tables/news_controller_spec.rb:63:in `block (5 levels) in <top (required)>'

Any thoughts? thank you

pirj commented 3 years ago

Judging by the spec name you're using a controller spec, which is according to its docs:

A controller spec is an RSpec wrapper for a Rails functional test
([ActionController::TestCase::Behavior](https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/test_case.rb)).
It allows you to simulate a single http request in each example, and then
specify expected outcomes such as:

* rendered templates
* redirects
* instance variables assigned in the controller to be shared with the view
* cookies sent back with the response

For testing the content of the page, Feature specs would be more appropriate, and they provide Capybara matchers, e.g. have_text and have_css:

expect(page).to have_css("h1", text: "Newss")
expect(page).to have_css("h2").exactly(4).times

This syntax should work fine with aggregate_failures.

I'm afraid making Rails' assertions compatible with aggregate_examples might not be trivial.

I completely understand that rspec-rails:

A pull request to adjust those shortcomings is welcome.

woto commented 3 years ago

Ok, thank you for detailed answer. Kind regards