我有 2 个模型:文章和类别。文章取决于类别:为了创建文章,我必须先创建类别。我有 4 个文件:article.features、category.features、article_steps.rb、category_steps.rb
。在 article_steps.rb
的某处,我必须创建 Category 才能创建 Article 本身。但是在category_steps.rb
中已经定义了创建Category的代码。
如何在 article_steps.rb
中重复使用它?我可以在同一个模型中做到这一点,但有什么办法可以在不同的模型中做到这一点吗?
最佳答案
category_steps.rb
中定义的步骤可以在任何特征文件中使用。只需使用 article.features
中 category_steps.rb
中定义的 Given
步骤:
文章.功能
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
由于“测试”类别将在整个场景中使用,因此将此数据的创建移至场景背景
。接下来,在您的步骤定义文件中,定义上述步骤:
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
步骤定义的整体思想是促进多个场景和功能文件之间的代码重用。步骤定义不应绑定(bind)到功能文件。相反,它们应该足够通用,以便在多种情况下重复使用。
关于ruby-on-rails - 在 Cucumber 中重用 2 个不同模型之间的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28858140/