我现在正在使用 Cucumber 和 Rails 测试 View ,非常享受这种体验。我可以轻松地说:
Background:
Given I am logged in as a customer
Scenario: View the Welcome Page
When I go to the home page
Then I should be on the "Welcome" page
And I should see the following in the sidebar:
| selector | text |
| h3 | Search |
| .home-page | Home |
| .about-page | About |
现在我想知道,我怎样才能更进一步说:
And I should see the following colors on the "Welcome" page:
| selector | background |
| #content | white |
| #sidebar | grey |
| #navigation | blue |
我觉得我看到可以使用 Node.js 或其他服务器端 javascript 之类的东西来做到这一点,因为它完全依赖于浏览器。有没有办法做到这一点,也许只在 Safari 和 Firefox 中使用 Selenium?
我只想主要测试颜色和字体,不一定是跨浏览器疯狂的布局 b/c。我怎么能这样做?也许有点Jasmine与 Cucumber ?
谢谢!
更新
感谢@idlefingers,这里有一些有用的东西:
设置: cucumber 、 capybara 。
features/support/env.rb:
Capybara.javascript_driver = :selenium
*features/step_definitions/css_steps.rb:*
Then /^I should see the color "([^"]+)" on the ([^"]+)$/ do |color, selector|
element_color = page.evaluate_script('$("##{selector}").css("border-left-color");') # "rgb(221, 221, 221)"
assert_equal color, some_color_conversion_method(element_color)
end
features/some.feature:
And I should see the color "red" on the sidebar
如果有更好的方法,我很想知道!
最佳答案
有时要求元素是某种颜色。可以使用 Jasmine 等工具对此进行测试,但由于您想要验证最终显示是否正确,因此基于浏览器的集成测试是正确的工具。 (要让它在 Jasmine 中工作,你必须做更多的工作,并最终得到一个不太有效的测试......无论如何......)
我写了一个simple jQuery plugin called Color Spy能够查询元素的颜色。你可以问:
$(...).backgroundColor()
$(...).colorColor()
该插件遍历计算颜色的 DOM。
要让它在 selenium 测试的上下文中工作,您需要:
- 确保插件可用。您可以只将它包含在您的页面中,或者有多种方法可以动态地引入它。
- 编写一个
element_color(selector)
测试辅助函数。这将需要使用整个get_eval
恶作剧来动态执行一些 Javascript。 - 正常使用
assert_equal
。 (我的 jsutils 存储库中也有一些 Javascript 函数来断言颜色的“视觉接近度”——但这是一个不同的问题。)
希望这对您有所帮助。
关于ruby-on-rails - 有没有一种方法可以测试(单元/集成)CSS 是否应用于预期的 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5042721/