Help me understand this syntax in railstutorial.org (the section on Factory Girl)
I am in chapter 7 of the railstutorial.org, and the author is starting to explain less and less of the syntax and details of the course.
I dont understand the following syntax he uses when creating a user with Factory Girl:
Factory.define :user do |user|
user.name "Michael Har开发者_高级运维tl"
user.email "mhartl@example.com"
user.password "foobar"
user.password_confirmation "foobar"
end
I am not copying and pasting the code, so initially, after reading, I wrote my code like this:
user.name = 'Michael Hartl'
etc
and the tests didnt run. After rereading that section, I saw that the author doesnt use the =. What does this mean? If I understood correctly, Factory girl creates a instance of User, and then assigns it these attributes. So how is user.name = 'whatever' incorrect?
I really hate not understanding stuff when doing tutorials, so I'm stuck here until I make sense of it...
This is ruby block syntax and you'll find it everywhere in rails. Look at your migrations for example. What's confusing you is the syntax of assignment and the fact that brackets/braces are (generally) optional in ruby. This allows more readable code which might otherwise be:
Factory.define :user do |user|
user.name("Michael Hartl")
user.email("mhartl@example.com")
user.password("foobar")
user.password_confirmation("foobar")
end
Further reading
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.
精彩评论