RSpec 被设计为单元测试框架,因此从中获得完美的功能测试行为可能有点困难。在 RSpec 的哲学测试中must独立。当您使用时尤其重要autotest:在这种情况下,执行顺序确实是不可预测的。悲伤但真实。
Still, of course you can save some state between test using global ($a
) or instance (@a
, not sure here) variables. Anyway you need to move if
into it
block so that it will be executed in time. You may use pending https://github.com/dchelimsky/rspec/wiki/Pending-Examples keyword to interrupt a test without failing it in case if pre-condition is not met.
BUT
我确信最好的解决方案是避免金锤子 http://en.wikipedia.org/wiki/Law_of_the_instrument反模式,而不是在单元测试框架中编写功能测试。您不想测试一些单独的功能。你确实想测试场景。所以我建议尝试一些场景测试套件。
Behold, Cucumber http://cukes.info/!用法很简单:
- 定义参数化场景stepsRuby 中,以及 RSpec 风格的期望
- 用自然语言编写场景(是的,不仅是英语,甚至是俄语或其他语言 - 正则表达式的力量就在你身边)
就你而言,你将有features/step_definitions/gui_steps.rb
就像是
Given /I pushed a button "(.*)"/ do |name|
@buttons.find(name).click() # This line is pseudo-code, you know
end
以及类似的检查窗口打开情况等(请参阅examples https://github.com/cucumber/cucumber/blob/master/examples/i18n/en/features/step_definitons/calculator_steps.rb)。然后您可以以任何方式组合定义的步骤,例如您的两个场景可能看起来像
Scenario: Feature 1
Given I pushed a button "go"
And I focus on opened window
When I trigger "feature 1"
Then I should se "result 1" in text area
Scenario: Feature 2
Given I pushed a button "go"
And I focus on opened window
When I trigger "feature 2"
Then I should se "result 2" in text area
在这两种情况下,如果场景的某个步骤失败(例如我专注于打开的窗户— 如果未打开),后续步骤不执行——如你所愿。作为奖励,您将获得极其发生的情况以及步骤的详细输出(请参阅网站上的图片)。
好消息是您并不总是需要自己定义所有步骤。例如,当您测试 Web 应用程序时,您可以使用 webrat 步骤来执行典型的操作,例如当我转到 url/a/b/c 时 and 然后我应该在页面上看到文本“foo”。我不知道你使用哪个GUI测试框架,但可能已经有它的步骤,所以我建议你谷歌一下Cucumber%框架名称%。即使没有,编写一次这些步骤也不会比尝试从 RSpec 制作 Cucumber 更困难。