【问题标题】:Re-using the code between 2 different models in Cucumber在 Cucumber 的 2 个不同模型之间重用代码
【发布时间】:2015-03-04 15:22:15
【问题描述】:

我有 2 个模型:文章和类别。文章依赖于分类:为了创建文章,我必须先创建分类。我有 4 个文件:article.features, category.features, article_steps.rb, category_steps.rb。在article_steps.rb 的某个地方,我必须创建类别才能创建文章本身。但是在category_steps.rb 中已经定义了创建类别的代码。

如何在article_steps.rb 中重复使用它?我可以在同一个模型中做到这一点,但有没有办法在不同的模型中做到这一点?

【问题讨论】:

  • FactoryGirl 不能处理吗?

标签: ruby-on-rails ruby testing cucumber


【解决方案1】:

category_steps.rb 中定义的步骤可用于任何功能文件。只需在article.features 中使用category_steps.rb 中定义的Given 步骤即可:

article.features

Feature: Articles
  In order to ...
  As a ...
  I want to ...

Background:
  Given the "Test" Category exists

Scenario: Creating an Article
  When I create an Article with the following attributes:
    | Title        | Body      |
    | Just Testing | Test test |
  And the "Just Testing" Article is in the "Test" Category
  Then an Article should exist with the following attributes:
    | Title        | Body      |
    | Just Testing | Test test |
  And the "Just Testing" Article should be in the "Test" Category

由于“测试”类别将在整个场景中使用,因此将此数据的创建移至场景Background。接下来,在您的步骤定义文件中,定义上述步骤:

category_steps.rb

Given /^the "(.*?)" Category exists$/ do |category_name|
  Category.create! :name => category_name
end

article_steps.rb

When /^I create an Article with the following attributes:$/ do |table|
  article = Article.new
  # Loop over the rows and columns to set properties on article
  article.save!
end

When /^the "(.*?)" Article is in the "(.*?)" Category$/ do |article_title, category_name|
  article = Article.find_by_title article_title
  article.category = Category.find_by_name category_name
  article.save!
end

Then /^an Article should exist with the following attributes:$/ do |table|
  expected = Article.new
  # Loop over rows and columns of table to set properties on article
  actual = Article.find_by_title expected.article_title

  # Compare expected and actual for differences
  expect(expected.title).to eq actual.title
  expect(expected.body).to eq actual.body
end

Then /^the "(.*?)" Article should be in the "(.*?)" Category$/ do |article_title, category_name|
  article = Article.find_by_title article_title
  expect(article.category.name).to eq category_name
end

步骤定义的整个想法是促进多个场景和功能文件之间的代码重用。步骤定义不应绑定到功能文件。相反,它们应该足够通用,可以在多种情况下重复使用。

【讨论】:

  • 在创建文章时,如何知道 category_id?
  • @AlexanderSupertramp:我已经更新了我的答案。这应该让您更好地了解如何在场景甚至功能之间重用步骤定义。
猜你喜欢
  • 2013-12-18
  • 2011-10-21
  • 2014-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多