1

我在railstutorial.org 的第 7 章,作者开始解释越来越少的语法和课程细节。

我不明白他在使用 Factory Girl 创建用户时使用的以下语法:

 Factory.define :user do |user|
  user.name                  "Michael Hartl"
  user.email                 "mhartl@example.com"
  user.password              "foobar"
  user.password_confirmation "foobar"
end

我不是在复制和粘贴代码,所以最初,在阅读之后,我编写了这样的代码:

user.name = 'Michael Hartl'
etc

并且测试没有运行。重读那部分后,我看到作者没有使用=。这是什么意思?如果我理解正确的话,Factory girl 会创建一个 User 实例,然后为其分配这些属性。那么 user.name = 'whatever' 是如何不正确的呢?

我真的很讨厌在做教程时不理解东西,所以我被困在这里直到我理解它......

4

2 回答 2

2

这是 ruby​​ 块语法,你会在 Rails 中到处找到它。例如,查看您的迁移。让您感到困惑的是赋值的语法以及括号/大括号(通常)在 ruby​​ 中是可选的这一事实。这允许更多可读的代码,否则可能是:

 Factory.define :user do |user|
  user.name("Michael Hartl")
  user.email("mhartl@example.com")
  user.password("foobar")
  user.password_confirmation("foobar")
end

进一步阅读

于 2011-07-30T13:02:51.317 回答
0

This: user.name = 'Michael Hartl' doesn't work, because the creator of Factory Girl chose a different syntax, namely: user.name "Michael Hartl". I guess you just have accept that Factory Girl works like this. If you want to know why you have to ask the creator.

于 2011-07-30T13:30:55.223 回答