Capybara/RSpec - 检查数组的内容

Capybara/RSpec - Checking the content of an array

我想重构我的代码,从可能的三行到只有一行。

这是片段:

    # 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")

我需要水豚 have_content 与 RSpec contain_exactly 的平衡。

类似于:

expect(stats).to contain_exactly("Impressions", "Clicks", "Average")

这导致:

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]">]

如何重构这个?

我认为这应该可行:

# capture an array of the three stats: impressions/clicks/AVT

stats = page.all('.sub').map(&:text)

expect(stats).to contain_exactly("Impressions", "Clicks", "Average")

更新

从 Rspec 3 开始,如果您正在寻找部分匹配,您可以执行以下操作:

expect(stats).to contain_exactly(
                                 a_string_matching(/Impressions/),
                                 a_string_matching(/Clicks/),
                                 a_string_matching(/Average/)
                                )