如何在Capybara中断言JQuery表达式?

时间:2018-02-07 14:37:08

标签: jquery capybara

我应该检查带有标签文章的元素,并且特定类是DOM中数组中的第一个元素。我写了JQuery表达女巫正在工作:

true

在控制台中检查只有Then(/^Tag "(.*)" has the first element "(.*)"/) do |text, identifier| page.execute_script("$($('#{text}')[0]).hasClass('#{identifier}')") end 元素返回Then Tag "article" has the first element "styles__highlighted___2C5Yh" 。之后我创建了这样的步骤定义:

0

在我的测试中:

0

它传递了{{1}}和另一个数字(当我运行测试时),但控制台中的jQuery表达式仅在{{1}}时返回true。我认为我应该以某种方式修改我的步骤定义文件,但不知道如何。

2 个答案:

答案 0 :(得分:0)

有两个技术问题。

  1. 您想要处理JS的结果,但是您使用的是execute_script而不是evaluate_script

  2. 你实际上并没有期待任何事情

  3. 如果我们解决了这两个问题,那么

    Then(/^Tag "(.*)" has the first element "(.*)"/) do |text, identifier|
      result = page.evaluate_script("$($('#{text}')[0]).hasClass('#{identifier}')")
      expect(result).to be true # RSpec - will be different if using minitest
    end
    

    这会修复你的代码,但是它真的不是测试你想要的东西的好方法,因为它会导致动态页面上的片状测试(没有等待重试)

    最佳解决方案取决于页面的确切结构。例如,如果所有'article'元素都是兄弟元素,那么你可以做类似

    的事情
    Then(/^The first article should be highlighted$/) do
      expect(page).to have_selector('article.styles__highlighted___2C5Yh:first-of-type')
    end
    

    一个不太理想的选择(虽然仍然比jQuery更好)将是

    first_article = find('article', match: :first)
    expect(first_article).to match_css('.styles__highlighted___2C5Yh')
    

答案 1 :(得分:0)

感谢。 修正了它以这种方式改变:

Then(/^Tag "(.*)" has the first element "(.*)"/) do |text, identifier|
  result = page.evaluate_script("$($('#{text}')[0]).hasClass('#{identifier}')")
  result.should be true
end