Capybara / RSpec - 检查阵列的内容

时间:2015-01-07 15:50:39

标签: ruby-on-rails rspec capybara

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

以下是片段:

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

我需要平衡Capybara 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]">]

如何重构这个?

1 个答案:

答案 0 :(得分:3)

我认为这应该有效:

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