Every time I’m creating fixtures for Rails application I’m being angry because any more or less considerable project needs tons of them. Most complicated thing is to track all relationships, validations, and to keep fixtures up to date. A few days ago Yurii Rashkovskii has released small utility — Fixturease. What if I would tell you that now you can create your fixtures using your models?
To install gem enter command:
1 | gem install fixturease |
It’s time to try something:
1 2 3 4 5 6 7 8 9 10 11 12 | # Loading Fixturease console for test mode. @mike = User.create(:login => 'mike', :password => 'pass') # <User:0x482ac18 @new_record_before_save=true, @attributes={"id"=>5, "password"=>"pass", "login"=>"mike", "created_at"=>Sat Jan 20 21:40:23 +0200 2007}, @errors=#<ActiveRecord::Errors:0x4827b08 @base=#<User:0x482ac18 ...>, @errors={}>, @new_record=false> @mike_post_1 = @mike.posts.create(:name => 'first post by mike') # <Post:0x4811bb4 @new_record_before_save=true, @attributes={"name"=>"first post by mike", "updated_at"=>Sat Jan 20 21:40:38 +0200 2007, "id"=>3, "user_id"=>5, "created_at"=>Sat Jan 20 21:40:38 +0200 2007}, @errors=#<ActiveRecord::Errors:0x4811510 @base=#<Post:0x4811bb4 ...>, @errors={}>, @new_record=false> @mike_post_2 = @mike.posts.create(:name => 'second post by mike') # <Post:0x48099dc @new_record_before_save=true, @attributes={"name"=>"second post by mike", "updated_at"=>Sat Jan 20 21:40:45 +0200 2007, "id"=>4, "user_id"=>5, "created_at"=>Sat Jan 20 21:40:45 +0200 2007}, @errors=#<ActiveRecord::Errors:0x48093d8 @base=#<Post:0x48099dc ...>, @errors={}>, @new_record=false> exit # Saving fixtures: # User [./spec/fixtures/users.yml]: mike # Post [./spec/fixtures/posts.yml]: mike_post_1 and mike_post_2 |
In this very simple case we just created one fixture for User model named mike and two for Post model named mike_post_1 and mike_post_2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | mike: id: 5 password: pass login: mike created_at: 2007-01-20 21:40:23.250000 +02:00 mike_post_1: name: first post by mike updated_at: 2007-01-20 21:40:38.765000 +02:00 id: 3 user_id: 5 created_at: 2007-01-20 21:40:38.765000 +02:00 mike_post_2: name: second post by mike updated_at: 2007-01-20 21:40:45.562000 +02:00 id: 4 user_id: 5 created_at: 2007-01-20 21:40:45.562000 +02:00 |
You can always load fixtures to current environment using command load_fixtures! (or command-line switch -l). It allows you to use previously created fixtures to build new ones.
I like unit tests but I hate to write fixtures. This nice gem allows me to relax and to get pleasure from work.
WOW !! Really Really interesting !! Thank you !
Извиняюсь за оффтоп, подскажи, какой плагин использовал для мультиязычности?
С тем же результатом можно написать:
2
3
4
5
6
7
8
9
10
password: pass
login: mike
mike_post_1:
name: first post by mike
user: mike
mike_post_2:
name: second post by mike
user: mike
А еще у вас сломана openid-аутентификация на блоге.