`

factory_girl 使用帮助

阅读更多
Getting Started
Update Your Gemfile
If you're using Rails, you'll need to change the required version of factory_girl_rails:

gem "factory_girl_rails", "~> 3.0"
If you're not using Rails, you'll just have to change the required version of factory_girl:

gem "factory_girl", "~> 3.0"
Once your Gemfile is updated, you'll want to update your bundle.

Using Without Bundler
If you're not using Bundler, be sure to have the gem installed and call:

require 'factory_girl'
Once required, assuming you have a directory structure of spec/factories or test/factories, all you'll need to do is run

FactoryGirl.find_definitions
If you're using a separate directory structure for your factories, you can change the definition file paths before trying to find definitions:

FactoryGirl.definition_file_paths = %w(custom_factories_directory)
FactoryGirl.find_definitions
If you don't have a separate directory of factories and would like to define them inline, that's possible as well:

require 'factory_girl'

FactoryGirl.define do
  factory :user do
    name 'John Doe'
    date_of_birth { 21.years.ago }
  end
end
Defining factories
Each factory has a name and a set of attributes. The name is used to guess the class of the object by default, but it's possible to explicitly specify it:

# This will guess the User class
FactoryGirl.define do
  factory :user do
    first_name "John"
    last_name  "Doe"
    admin false
  end

  # This will use the User class (Admin would have been guessed)
  factory :admin, class: User do
    first_name "Admin"
    last_name  "User"
    admin      true
  end
end
It is highly recommended that you have one factory for each class that provides the simplest set of attributes necessary to create an instance of that class. If you're creating ActiveRecord objects, that means that you should only provide attributes that are required through validations and that do not have defaults. Other factories can be created through inheritance to cover common scenarios for each class.

Attempting to define multiple factories with the same name will raise an error.

Factories can be defined anywhere, but will be automatically loaded if they are defined in files at the following locations:

test/factories.rb
spec/factories.rb
test/factories/*.rb
spec/factories/*.rb
Using factories
factory_girl supports several different build strategies: build, create, attributes_for and stub:

# Returns a User instance that's not saved
user = FactoryGirl.build(:user)

# Returns a saved User instance
user = FactoryGirl.create(:user)

# Returns a hash of attributes that can be used to build a User instance
attrs = FactoryGirl.attributes_for(:user)

# Returns an object with all defined attributes stubbed out
stub = FactoryGirl.build_stubbed(:user)

# Passing a block to any of the methods above will yield the return object
FactoryGirl.create(:user) do |user|
  user.posts.create(attributes_for(:post))
end
No matter which strategy is used, it's possible to override the defined attributes by passing a hash:

# Build a User instance and override the first_name property
user = FactoryGirl.build(:user, first_name: "Joe")
user.first_name
# => "Joe"
If repeating "FactoryGirl" is too verbose for you, you can mix the syntax methods in:

# rspec
RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end

# Test::Unit
class Test::Unit::TestCase
  include FactoryGirl::Syntax::Methods
end

# Cucumber
World(FactoryGirl::Syntax::Methods)
This would allow you to write:

describe User, "#full_name" do
  subject { create(:user, first_name: "John", last_name: "Doe") }

  its(:full_name) { should == "John Doe" }
end
Lazy Attributes
Most factory attributes can be added using static values that are evaluated when the factory is defined, but some attributes (such as associations and other attributes that must be dynamically generated) will need values assigned each time an instance is generated. These "lazy" attributes can be added by passing a block instead of a parameter:

factory :user do
  # ...
  activation_code { User.generate_activation_code }
  date_of_birth   { 21.years.ago }
end
In addition to running other methods dynamically, you can use FactoryGirl's syntax methods (like build, create, and generate) within dynamic attributes without having to prefix the call with FactoryGirl.. This allows you to do:

sequence(:random_string) {|n| LoremIpsum.generate }

factory :post do
  title { generate(:random_string) } # instead of FactoryGirl.generate(:random_string)
end

factory :comment do
  post
  body { generate(:random_string) }  # instead of FactoryGirl.generate(:random_string)
end
Aliases
Aliases allow you to use named associations more easily.

factory :user, aliases: [:author, :commenter] do
  first_name    "John"
  last_name     "Doe"
  date_of_birth { 18.years.ago }
end

factory :post do
  author
  # instead of
  # association :author, factory: :user
  title "How to read a book effectively"
  body  "There are five steps involved."
end

factory :comment do
  commenter
  # instead of
  # association :commenter, factory: :user
  body "Great article!"
end
Dependent Attributes
Attributes can be based on the values of other attributes using the evaluator that is yielded to lazy attribute blocks:

factory :user do
  first_name "Joe"
  last_name  "Blow"
  email { "#{first_name}.#{last_name}@example.com".downcase }
end

FactoryGirl.create(:user, last_name: "Doe").email
# => "joe.doe@example.com"
Transient Attributes
There may be times where your code can be DRYed up by passing in transient attributes to factories.

factory :user do
  ignore do
    rockstar true
    upcased  false
  end

  name  { "John Doe#{" - Rockstar" if rockstar}" }
  email { "#{name.downcase}@example.com" }

  after(:create) do |user, evaluator|
    user.name.upcase! if evaluator.upcased
  end
end

FactoryGirl.create(:user, upcased: true).name
#=> "JOHN DOE - ROCKSTAR"
Static and dynamic attributes can be ignored. Ignored attributes will be ignored within attributes_for and won't be set on the model, even if the attribute exists or you attempt to override it.

Within FactoryGirl's dynamic attributes, you can access ignored attributes as you would expect. If you need to access the evaluator in a FactoryGirl callback, you'll need to declare a second block argument (for the evaluator) and access ignored attributes from there.


more: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md
分享到:
评论

相关推荐

    factory_bot:用于将Ruby对象设置为测试数据的库

    从factory_girl过渡? 查看 。 文献资料 您应该在上找到有关版本的文档。 有关定义和使用工厂的信息,请参见 。 我们还提供,可在Upcase上免费获得。 安装 将以下行添加到Gemfile中: gem 'factory_bot' 并从您...

    factory_factory_girl:可以帮助您生成工厂文件的宝石

    例如,您使用FFaker::Job.title生成所有name或title的值,并使用FFaker::Lorem.paragraph生成description或content的值。 然后,您只需要将这些方法复制并粘贴到服务器工厂,甚至服务器项目工厂中的服务器列中即可...

    factory_bot_instruments:基准测试,跟踪和调试Factory Girl模型的工具

    Factory Bot Instruments在以下三个方面提供帮助: 缓慢的测试套件:Factory Bot用于Rails中的大量测试。 即使在您的一家工厂中进行很小的性能改进,也可以显着提高整个测试套件的速度。 提示:运行FactoryBot....

    nested_attr:用于测试使用Factory Girl和Formastic Forms的Rails应用程序的帮助程序插件(例如Active Admin)

    一个小插件,可帮助您在使用FactoryGirl时轻松测试Active Admin表格格式。 描述 当我们执行FactoryGirl.attributes_for(:factory_name)时,FactoryGirl不提供嵌套属性,但是当我们以活动管理员形式测试控制器时...

    factory-girl-typeorm:Typeorm适配器,适用于工厂女孩

    **工厂女孩(Factory Girl)与TypeORM适配器** 工厂女孩是一个流行的测试工具,主要用于创建对象的模拟数据,尤其在JavaScript开发中广泛使用。它帮助开发者快速生成测试数据,简化测试场景的设置,提高测试效率。...

    定语从句练习

    根据提供的文件信息,我们可以归纳出一系列关于定语从句的知识点。下面将对这些知识点进行详细解析。...掌握好定语从句不仅能够帮助我们更准确地表达意思,还能够在写作和口语交流中提升语言的流畅度和准确性。

    ing形容词和ed形容词经典练习.doc

    从部分内容来看,练习题涵盖了选择题、填空题等多种题型,旨在帮助学习者巩固对这两种形容词的理解和使用。例如: 1. 第一题:"Who _____ over there now?" 此题考察现在进行时,正确答案是"C. is singing",因为...

    设计模式源代码

    创建型模式如单例(Singleton)、工厂方法(Factory Method)和抽象工厂(Abstract Factory),它们关注于对象的创建过程,使代码与具体的实例化过程解耦。结构型模式如适配器(Adapter)、装饰器(Decorator)和...

    Unit2__Section__A(Grammar__Focus-4c)精品课件.ppt

    此外,课件还提供了一些例句和填空练习,帮助学生理解和掌握这两种感叹句结构。通过这些练习,学生可以更好地运用感叹句来表达他们的情绪和感受,增强语言表达的生动性和感染力。记住,感叹句的正确使用能有效提升...

    bootstrapper:一个Rails插件,可帮助引导和播种数据库

    该文件将包含以下内容: Bootstrapper.for :development do |b|endBootstrapper.for :production do |b|endBootstrapper.for :test do |b|endBootstrapper.for :staging do |b|end使用Factory Girl和Forgery之类的...

    Android Koin2基本使用的那件事儿

    factory { Girl() } } ``` 在你的 Activity 或其他组件中,你可以通过 `by inject<T>` 或 `get()` 来获取依赖: ```kotlin class Simple1Activity : AppCompatActivity() { private val girl by inject...

    mywanderlust:一个网络和移动应用程序,可帮助组织多人之间的旅行计划。 Wanderlust 是开源软件,可以称为以下之一

    流浪癖我开发这个应用程序是为了帮助...发展模板引擎: ERB 测试框架:RSpec 和 Factory Girl 前端框架:Twitter Bootstrap (Sass) 表单生成器:SimpleForm 认证:设计授权:无电子邮件该应用程序配置为使用 Mandrill

    frank:因为聪明的人值得自动化

    4. **工厂机器人 (FactoryBot)**:FactoryBot(原名Factory Girl)是一个Ruby的测试辅助工具,用于创建数据库中的对象实例,特别是在测试环境中。它可以减少创建复杂对象的样板代码,提高测试的效率和清晰度。 5. *...

    高中英语语法大全

    - _There are twenty boy-students and twenty-three girl-students in the class._ (班里有二十个男生和二十三个女生。) - **连接词“either...or...”与“neither...nor...”**:谓语动词的形式取决于这些连接...

    ruby on rails 3

    8. **Testing**:Rails 3增强了测试框架,支持Shoulda、Factory Girl等库,使得编写测试用例更加高效。同时,Test::Unit和RSpec都得到了改进,提供了一流的测试体验。 9. **Internationalization (i18n)**:Rails 3...

    GOF23 设计模式与MM

    #### FACTORY(工厂模式) 工厂模式是一种常见的设计模式,它提供了创建对象的最佳方式。在这个模式下,通常会定义一个创建对象的接口,但是让子类决定实例化哪一个类。工厂模式确保一个类只会产生一个实例,并且...

    java23种设计模式

    示例中的代码展示了简单的工厂模式,`Factory`类根据传入的参数创建`Boy`或`Girl`对象。当需要创建新的对象类型时,只需扩展工厂类即可,无需修改现有的客户端代码。 2. 建造者模式(Builder Pattern): 建造者...

    谈Java的23种设计模式

    在上述例子中,`Factory`类根据传入的参数返回`Boy`或`Girl`对象。这样,客户端代码无需关心具体的对象创建逻辑,只需要与工厂交互即可。 2. 建造者模式(Builder Pattern): 建造者模式将复杂对象的构建与其表示...

    高中英语主谓一致讲解教案,高中英语主谓一致知识点总结.docx

    例如:"The girl has found her mother." 在这个例子中,"girl"是单数主语,所以谓语动词"has found"也是单数形式。 2. 意义一致原则:有时候,主语在意义上是单数,尽管它可能是复数形式。比如:"Three years in a...

    ruby on rails 敏捷开发,3.1 pdf and epub format

    另外,测试部分引入了Shoulda和Factory Girl等测试工具,它们可以帮助开发者编写更简洁、更高效的测试用例。 Rails 3.1还引入了CoffeeScript作为默认的JavaScript语言,这是一种语法糖,它可以编译成标准的...

Global site tag (gtag.js) - Google Analytics