什么是factory_girl瞬态属性?我为什么要用一个? [英] What are factory_girl transient attributes? Why would I use one?

查看:83
本文介绍了什么是factory_girl瞬态属性?我为什么要用一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Thoughtbot阅读了,但它仍然使我感到困惑.

I read this from Thoughtbot but it's still confusing to me.

这是他们的示例:

factory :user do
  transient 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

create(:user, upcased: true).name
#=> "JOHN DOE - ROCKSTAR"

所以

  1. .upcased是模型上的真实属性吗?
  2. transient块实际上在做什么?设置可以在工厂使用的变量?
  3. 什么是evaluator?是否总是需要最后通过?如果您的create函数使用特征,瞬态并具有多个值怎么办?
  1. Is .upcased a real attribute on the model?
  2. What is the transient block really doing? Setting variables that can then be used in the factory?
  3. What is evaluator? Does it always need to be passed last? What if your create function uses traits, transients, and has multiple values?

推荐答案

factory_bot的瞬时属性"根本不是属性.它们只是工厂方法调用的参数,您的工厂内部代码可以使用这些参数.因此,在您的示例中,不,upcased不是模型属性.

factory_bot's transient 'attributes' aren't attributes at all; they're just parameters to the factory method call that can be used by your code inside the factory. So, in your example, no, upcased isn't a model attribute.

transient块列出了不是 属性的属性"名称(即,传递给工厂方法的哈希中的键).在新创建的模型实例上设置属性时,factory_bot会忽略它们,除非您在工厂定义中编写代码以告诉factory_bot对它们执行某些操作.

The transient block lists 'attribute' names (that is, keys in the hash passed to the factory method) that are not attributes. factory_bot ignores them when setting attributes on the newly created model instance unless you write code in the factory definition to tell factory_bot to do something with them.

evaluator是传递给factory_bot回调的对象.它始终是第二个块参数;模型对象始终是第一个参数.从概念上讲,它就像Ruby的binding.您可以要求它提供参数哈希中任何键的值,而不管它是实际属性还是瞬态属性".

evaluator is an object passed to factory_bot callbacks. It's always the second block parameter; the model object is always the first parameter. It's conceptually like Ruby's binding. You can ask it for the value of any key in the argument hash, regardless of whether it's an actual attribute or a transient 'attribute'.

就工厂方法的参数而言,特性和瞬态属性不会相互影响,因为特征是标量,而瞬态属性是参数哈希的一部分.参数哈希中可以包含任意数量的真实属性和瞬态属性".

Traits and transient attributes don't affect each other as far as arguments to factory methods are concerned, since traits are scalar and transient attributes are part of the argument hash. Any number of real attributes and transient 'attributes' can be in the argument hash.

这是该记录的factory_bot文档: https://github.com/Thoughtbot/factory_bot/blob/master/GETTING_STARTED.md

Here's the factory_bot documentation for the record: https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md

这篇关于什么是factory_girl瞬态属性?我为什么要用一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆