在Cucumber特性(Rails 3)中使用Factory Girl步骤定义

7
我将使用Cucumber和Factory Girl。下面是相关代码:

  Given I am not logged in
  And   the following user exists:
    | login  | email               | password   | confirmation |
    | user50 | user50@mydomain.com | secret50   | secret 50    | 
 ....

引发以下错误:

Undefined step: "the following user exists:" (Cucumber::Undefined exception)
/home/user/RubymineProjects/project/features/sign_in.feature:9:in `And the following user exists:

You can implement step definitions for undefined steps with these snippets:
And /^the following user exists:$/ do |table|
  # table is a Cucumber::Ast::Table
  pending # express the regexp above with the code you wish you had
end

我已经安装了factory_girl_rails(甚至RubyMine的代码补全功能也与Factory Girl步骤兼容...)

#Gemfile
group :test do
   gem "cucumber-rails", ">= 0.3.2"
   gem "factory_girl_rails"
 end

#features/support/env.rb
require 'factory_girl'
require 'factory_girl/step_definitions'

有什么想法吗?谢谢


更新:感谢 @sj26 和 @twmills,我意识到我忘记使用Factory Girl创建了一个名为:user的工厂。一旦我创建了它,一切都正常了。


1
你有一个users.rb的工厂文件吗? - twmills
4个回答

11

对于那些现在尝试使用FactoryGirl助手的人:

从FactoryGirl 3.5.0开始,这些步骤助手已被弃用并在4.0.0中删除:http://robots.thoughtbot.com/post/25650434584/writing-better-cucumber-scenarios-or-why-were

从FactoryGirl 3.5.0开始,使用任何FactoryGirl生成的步骤定义都将打印出警告。根据SemVer,我们将在FactoryGirl 4.0.0发布中完全删除步骤定义。我想现有代码将被提取到类似于Cucumber Rails "training wheels"的gem中,并附带一个不错的警告提示开发人员不要使用这些步骤。

因此,如果您想在Cucumber中使用FactoryGirl,则应在自己的步骤定义中使用它。


好的。如果您的答案获得至少3个赞,我会考虑将您的答案标记为正确答案。(我不再使用cucumber,因此无法检查) - Dorian

7

首先需要引入你的工厂 factory_girl/step_definitions ,它将遍历你定义的工厂为每一个步骤定义。

我在features/support/factory_girl.rb中使用这个:

# Require factories...
require 'spec/factories'

# Then define steps based on factories.
require 'factory_girl/step_definitions'

我得到了no such file to load -- spec/factories (LoadError)的错误,即使我有那个文件夹和一些在rspec测试中(成功)使用的工厂。我还尝试了require '../../spec/factories',但仍然没有运气。像往常一样,RubyMine的代码完成可以找到所有内容...非常烦人,我想使用Factory Girl提供的默认步骤而不编写自己的步骤。 - Dorian
你确定你有一个 factory :user 吗?能不能把你的用户模型、工厂文件、黄瓜支持和黄瓜特性放到 gist 上? - sj26
谢谢,问题已解决。我没有:user工厂。抱歉,这是一个新手问题(我第一次使用Factory Girl)。 - Dorian

1

请在 features/step_definitions/user_steps.rb 中尝试此方法

Given /^the following user exists:$/ do |users|
  users.hashes.each do |user|
    Factory(:user,user)
  end
end

虽然您可能希望这样:

Given /^the following users:$/ do |users|
  etc..

这会复制factory_girl的step_definitions的功能,但是代码会变得冗长。 - sj26
如果可能的话,我想使用factory_girl的step_definitions。(如果不行,我可能会使用这个解决方法)。感谢@sj26和@MacksMind。 - Dorian
@sj26 旧习难改。当我开始使用Factory Girl时,它没有包含步骤定义。需要进行切换。 - MacksMind
那么,你会如何使用factory_girl的step_definitions编写步骤定义呢? - thoughtpunch

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接