Reputation: 3923
I'd like to refactor my code, from potentially three lines to just one.
Here's the snippet:
# capture an array of the three stats: impressions/clicks/AVT
stats = page.all('.sub')
# check our array....
expect(stats[0]).to have_content("Impressions")
expect(stats[1]).to have_content("Clicks")
expect(stats[2]).to have_content("Average")
I need a balance of the Capybara have_content
with the RSpec contain_exactly
.
Something like:
expect(stats).to contain_exactly("Impressions", "Clicks", "Average")
Which results in:
Failure/Error: expect(stats).to contain_exactly("Impressions", "Clicks", "Average")
expected collection contained: ["Average", "Clicks", "Impressions"]
actual collection contained: [#<Capybara::Element tag="div" path="/html/body/div[2]/div[2]/div/div[1]/div[1]/div[1]">, #<Capybara::Element tag="div" path="/html/body/div[2]/div[2]/div/div[1]/div[2]/div[1]">, #<Capybara::Element tag="div" path="/html/body/div[2]/div[2]/div/div[1]/abbr/div[1]">]
the missing elements were: ["Average", "Clicks", "Impressions"]
the extra elements were: [#<Capybara::Element tag="div" path="/html/body/div[2]/div[2]/div/div[1]/div[1]/div[1]">, #<Capybara::Element tag="div" path="/html/body/div[2]/div[2]/div/div[1]/div[2]/div[1]">, #<Capybara::Element tag="div" path="/html/body/div[2]/div[2]/div/div[1]/abbr/div[1]">]
How would one refactor this?
Upvotes: 0
Views: 1194
Reputation: 1500
I think this should work:
# capture an array of the three stats: impressions/clicks/AVT
stats = page.all('.sub').map(&:text)
expect(stats).to contain_exactly("Impressions", "Clicks", "Average")
Update
Starting with Rspec 3, you could do the following, if you're looking for partial matching:
expect(stats).to contain_exactly(
a_string_matching(/Impressions/),
a_string_matching(/Clicks/),
a_string_matching(/Average/)
)
Upvotes: 3