Capybara:测试 CSS PsuedoElements 中的内容

问题描述 投票:0回答:2

我正在开发一个应用程序,其中文本有条件地出现在

::before
伪元素的内容属性中并呈现在页面上。在代码更改导致此重要文本意外消失后,我希望能够编写测试,以便在再次发生该错误时捕获该错误,但从伪选择器中获取内容存在挑战。我一直在寻找类似的东西:

#scss
.content-div {
  &.condition-true {
    &:before {
      content: "conditional text";
    }
  }
}

#coffeescript
if @someCondition
  $('content-div').addClass('condition-true')
else
  $('content-div').removeClass('condition-true')

#spec
context "when true" do
  it "should have the conditional text" do
    # do thing that makes it true
    expect( page ).to have_content("conditional text")
  end
end

解决方案并不那么容易,我想我应该在这里分享并让其他人评论,或者提供其他解决方案。

我正在使用 Capybara 2.3.0 和 Poltergeist 1.5.1。

ruby-on-rails-4 capybara rspec2 poltergeist
2个回答
3
投票

关键是将一段代码传递给

page.evaluate_script
,以及 Javascript 的
getComputedStyle()
函数。

content_array = page.evaluate_script <<-SCRIPT.strip.gsub(/\s+/,' ')
  (function () {
    var elementArray = $('.desired-css-selector');
    var contentArray = [];
    for (var i = 0, tot=elementArray.length; i < tot; i++) {
      var content = window.getComputedStyle( elementArray[i], ':before' ).getPropertyValue('content');
      contentArray.push(content);
    }
    return contentArray;
  })()
SCRIPT
content_array.each { |c| c.gsub!(/\A'|'\Z/, '') }

expect( content_array ).to include("conditional text")

更新 - 简单示例:

我最近不得不做一个更简单的版本:

color = page.evaluate_script <<-SCRIPT
  (function () {
    var element = document.getElementById('hoverme');
    var color = window.getComputedStyle( element, ':hover' ).getPropertyValue('color');

    return color;
   })()
SCRIPT

0
投票

9年后,仍然是一个重要的问题!

我采纳了 @steel 的答案并将其转移到 ruby 函数:

# Note this has no waiting logic,
# so the chord needs to already be rendered
def assert_first_chord(chord)
  content = page.evaluate_script <<-SCRIPT
    (function () {
      var element = document.getElementsByClassName('chord')[0];
      var content = window.getComputedStyle(element, ':after').getPropertyValue('content');

      return content;
    })()
  SCRIPT
  assert_equal(chord, content.delete('"'))
end

assert_first_chord('G')

需要注意的重要一点是,这会立即获取元素,没有水豚魔法等待元素出现,因此您可能需要在使用此方法检查内容之前找到该元素。

© www.soinside.com 2019 - 2024. All rights reserved.