2014-10-09 61 views
1

我正在研究一个应用程序,其中文本有条件地出现在::before伪元素的内容属性中并呈现在页面上。代码更改导致此重要文本意外消失后,我希望能够编写能够在错误再次发生时捕获错误的测试,但是存在挑战伪选择器内容的挑战。我正在寻找类似的东西:水豚:测试CSS中的内容PsuedoElements

#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 

解决方案不是那么容易,我想我会在这里分享,让别人评论,或提供其他解决方案。

我使用的是水豚2.3.0和Poltergeist 1.5.1。

回答

1

关键是将一段代码传递给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