【问题标题】:When to test what with Cucumber and Rails何时使用 Cucumber 和 Rails 进行测试
【发布时间】:2025-12-24 06:20:33
【问题描述】:

当我在 Cucumber 和 Ruby on Rails 中编写测试时,我一直在问自己这个问题。我什么时候测试“如何创建 X”与“可以创建 X”

我如何创建 X 似乎包括测试用户创建 X 所需的实际步骤,通常是通过表单。 比如导航到新页面,点击“create X”链接,填写表格点击create,就可以看到X已经创建好了。

另一种选择,“可以创建 x”,是系统、模型和控制器是否处理创建 X 的能力,也就是它们是否正确连接。

我通常会同时测试这两种情况吗?我刚刚开始为我的业余项目写一个问答部分,并且无法决定是否编写类似的测试(我已经删除了背景,它们有点长)

When I click "Ask the seller a question"
And I fill out the form with a question and submit the form
Then I should see that the question has been created
And the user that posted the job has been notified

还是应该更像

When I ask the seller a question
Then I should see that the question has been posted
And the user that posted the job has been notified

区别在于我是通过表单还是工厂创建它,对吗? Rspec 在哪里发挥作用,我认为它应该测试“可以创建 X”,这是否意味着我不应该使用 cucumber 来测试它?

我想我本质上是在看“我用黄瓜测试什么”,但也许我让这变得更复杂,但我自己无法得出结论。你有任何见解都会很棒。

【问题讨论】:

    标签: ruby-on-rails unit-testing rspec cucumber functional-testing


    【解决方案1】:

    您描述为“我如何创建 X”的方法更好,因为您从用户角度进行测试,这对 Cucumber 来说更自然/更受欢迎。

    此外,从文档的角度来看,这种方法更好 -> 你描述了一些东西是如何工作的,而不是“预期的”。因此,如果您需要茶点或项目中有新开发人员 -> 您或他可以阅读一个场景。

    您可以在此处阅读有关用户视角测试的一些信息:http://www.businesstechnologyarticles.eu/testing-the-user-perspective-with-ruby-on-rails

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      现在我会以不同的方式回答。 Cucumber 场景应该更像是“可以创建 X”(我的意思是您的第二个示例),但仅在步骤中使用 Capybara,而很少使用 Ruby 代码、RSpec、FactoryGirl ...... 由于 web_steps 已从 Cucumber 中删除,您不应该尝试编写这样的步骤:

      When I click "Ask the seller a question"
      And I fill out the form with a question and submit the form
      

      这是一个非常糟糕的方法。

      第二个例子好多了

      When I ask the seller a question
      Then I should see that the question has been posted
      And the user that posted the job has been notified
      

      更多的是大体思路,不赘述

      但是您应该主要编写 Capybara 步骤,其中将包含有关“我如何创建 X”的所有详细信息。

      例子:

      When(/^I ask the seller a question$/) do
        click_link 'Ask the seller a question'
        fill_in 'my_form', with: 'My question'
        click_button 'Submit'
      end
      
      Then(/^I should see that the question has been posted$/) do
        expect(page).to have_selector '.alert', text: 'New question has been posted.'
        expect(page).to have_content 'Question: My question'
      end
      

      【讨论】: