ruby-on-rails - 在 Cucumber 中重用 2 个不同模型之间的代码

标签 ruby-on-rails ruby testing cucumber

我有 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.featurescategory_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/

相关文章:

ruby-on-rails - 无方法错误 : undefined method `current_sign_in_at' for #User:0x000055ce01dcf0a8 by using Devise_token_auth rails gem is not working

ruby - 在 rspec 中,为什么我不能在辅助类中使用 be_false 等?

android - 在 Android Studio 中的 Android Instrumentation 测试和单元测试之间共享代码

c# - 如何在使用 NUnit 或 XUnit 时将参数传递给 dotnet test 命令

ruby-on-rails - RSpec Rails 登录过滤器

ruby-on-rails - 有没有办法在 Rails Web 应用程序中获取客户端的实际端口?

javascript - ruby中的 'self'和javascript中的 'this'有什么区别

python - 在 FunkLoad 中测试发布到表单

ruby-on-rails - Rails 3 - 过滤器链暂停为 :authentication rendered or redirected

Ruby 和 JRuby 在同一台 Windows 7 计算机上