How to claim the number of items using Capybara with the correct error message?

I know that in Capybara you can do something like this:

page.should have_css("ol li", :count => 2) 

However, assuming that the page has, for example, only one corresponding element, the error is not very descriptive:

  1) initial page load shows greetings Failure/Error: page.should have_css("ol li", :count => 2) expected css "ol li" to return something 

Instead of this rather obscure error message, is there a way to write the statement in such a way that the error output would be something like "When matching" ol li ", expected: 2, found: 1". Obviously, I could create my own logic for this behavior - I ask, is there any way to do this "out of the box"?

For what it's worth, I use the Selenium driver and RSpec.

+65
rspec dsl capybara
Jul 18 2018-11-11T00:
source share
6 answers

I like it a lot better.

 expect(page).to have_selector('input', count: 12) 

https://github.com/jnicklas/capybara/blob/415e2db70d3b19b46a4d3d0fe62f50400f9d2b61/spec/rspec/matchers_spec.rb

+139
Jun 10 '13 at 21:19
source share

Well, as it seems, there is no support out of the box, I wrote this custom matches:

 RSpec::Matchers.define :match_exactly do |expected_match_count, selector| match do |context| matching = context.all(selector) @matched = matching.size @matched == expected_match_count end failure_message_for_should do "expected '#{selector}' to match exactly #{expected_match_count} elements, but matched #{@matched}" end failure_message_for_should_not do "expected '#{selector}' to NOT match exactly #{expected_match_count} elements, but it did" end end 

Now you can do things like:

 describe "initial page load", :type => :request do it "has 12 inputs" do visit "/" page.should match_exactly(12, "input") end end 

and get the output, for example:

  1) initial page load has 12 inputs Failure/Error: page.should match_exactly(12, "input") expected 'input' to match exactly 12 elements, but matched 13 

Now this is a trick, I will consider this part of Capybara.

+22
Jul 25 '11 at 10:20
source share

I think the following is simpler, gives a fairly clear conclusion, and eliminates the need for a special match.

 page.all("ol li").count.should eql(2) 

Then an error message is issued:

  expected: 2 got: 3 (compared using eql?) (RSpec::Expectations::ExpectationNotMetError) 
+15
Jul 10 '13 at 15:54
source share

How about this?

  within('ol') do expect( all('.opportunity_title_wrap').count ).to eq(2) end 
+7
Mar 10 '15 at 11:13
source share

The current (9/2/2013) recommendation recommended by Capybara is as follows ( source ):

page.assert_selector('p#foo', :count => 4)

+3
Sep 02 '13 at 18:53 on
source share

The answer from @pandaPower is very good, but the syntax for me was slightly different:

 expect(page).to have_selector('.views-row', :count => 30) 
-four
04 Sep '14 at 15:31
source share



All Articles