Customizing Generators in Rails 3

January 13, 2010

As you probably already know, Rails 3 is just around the corner. There are some pretty nice features being added and one of them is the ability to customize the way the generators work. I personally prefer Haml over ERB, RSpec over Test::Unit and Factory Girl over Fixtures. So let's see how we can configure a Rails 3 app to do that.

First, follow Yehuda's instructions on how to create a Rails 3 app. Next, you have to tell Rails that you want to use Haml, RSpec and Factory Girl. First, add this somewhere in the Gemfile:

gem "haml"

only :test do
  gem "rspec"
  gem "rspec-rails"
  gem "factory_girl"
end

Then, re-run the bundler and initialize the Haml plugin:

$ gem bundle
$ bin/haml --rails .

Finally, you have to install the custom generators for the frameworks that you want to use. I found a repo on github that already had RSpec, so I forked it and added Haml and Factory Girl. Clone the repo into the lib/generators directory of your app:

$ git clone git://github.com/pjb3/rails3-generators.git lib/generators

Now, in the config/application.rb file in your app, near the bottom there is a section related to config.generators. Put this in that section:

config.generators do |g|
  g.template_engine :haml
  g.test_framework :rspec, :fixture => true, :views => false
  g.fixture_replacement :factory_girl, :dir => "spec/factories"
end

Here is where we reap the benefits of the modularity in Rails 3. What this says is that we want to use Haml as the template enging, we want to use RSpec as the test framework and we want to generate fixtures with our generated specs, but we don't want to generate view specs and that instead of fixtures, we actually want to use factory girl and we want the factories to be put into spec/factories. Whew! So does this all work?

$ script/generate rspec:install
$ script/generate scaffold person name:string dob:date age:integer male:boolean bio:text

At this point you should see that Rails has generated what we want, which is scaffolding that uses Haml for the views, RSpec for the tests and Factory Girl for the fixtures. Run the migrations, start the server and open the browser http://localhost:3000/people to see your scaffolding in action.

Now if you try to actually run rake spec, you'll get an error, at least I do. I'm not sure that RSpec 1.X is going to ever work with Rails 3. I think the intent is for RSpec 2 to be compatible with Rails 3, so keep an eye out for that.

Posted in Technology | Tags Rails, HAML, RSpec, FactoryGirl

Comments Comments Feed

1. RSpec 2 will only be compatible with Rails 3.X and up. We are in the process of working out the Rails 3 compatibility bits right now.

# Posted By Chad Humphries on Wednesday, January 13 2010 at 12:57 PM

2. Thanks a million for this write-up! I was struggling for a day to get this working. I didn't realize I had to use 'script/generate rspec:install' instead of 'script/generate rspec'. Just to make sure I understand this correctly: The generator will create our spec files for models, etc., but we can't run the specs until RSpec 3 is available? How does this affect Cucumber?

# Posted By Curt on Tuesday, January 19 2010 at 8:23 PM

3. Great post Paul! I have to admit that I had no idea from where to start with generators. Thanks

Just one note, this fork here looks more up-to-date:
http://github.com/pjb3/rails3-generators

I suggesting cloning the generators from there.

# Posted By Marco on Friday, January 22 2010 at 12:39 PM

4. Hi and thanks for the article! But for me, the model generator still creates normal fixture even if i put

g.fixture_replacement :factory_girl, :dir => "spec/factories"

line there. Where is documentation about these configuration? Cheers!

# Posted By Jakub on Saturday, January 23 2010 at 2:03 PM

5. Based on this article (thanks!) I abstracted the HAML generators into a self-contained package.

See http://github.com/psynix/rails3_haml_scaffold_generator for more details.

# Posted By JohnM on Sunday, February 7 2010 at 7:53 AM

6. Thank you for the self-contained Haml package JohnM. The one in the article wasn't working for me.

# Posted By Peng Zhong on Monday, February 8 2010 at 5:11 AM

7. You may want to update the bundle install command for those using bundler 0.9.x. Instead of 'gem bundle' you run 'bundle install'.

Thanks for the rails 3 writeup!

# Posted By BJ Neilsen on Tuesday, February 9 2010 at 4:14 PM

8. Paul, pretty cool stuff and thanks for doing the legwork to start publicizing how to work with generators in Rails 3.
I'm trying to use your generators with Rails 3.0.0beta and the haml scaffold generator fails trying to find rails/generators/erb/scaffold/scaffold_generator. I am trying to get down to it but thought you might like to know... I guess parts of Rails 3 are still pretty unstable.
-Tyler

# Posted By Tyler on Monday, March 22 2010 at 6:39 PM

9. Great post, Paul. Not sure why you have this "script/generate rspec:install" ...I used "rails generate rspec:install" ...didn't see generate in the scripts dir and the guide (http://guides.rails.info/3_0_release_notes.html) said just to do "rails generate ..."

# Posted By Tony on Friday, June 11 2010 at 4:36 PM

10. Thanks for the post!

in the Gemfile:
only is deprecated , changed to a group

# Posted By Anatoliy on Monday, July 5 2010 at 3:59 PM

11. I've been out of the loop for a while, but I just discovered that as of beta4, :fixture_replacement is now an option to test_framework rather than a standalone generator. So for instance, this was required for me to use factory_girl:

g.test_framework :test_unit, :fixture_replacement => :factory_girl

# Posted By Gabe da Silveira on Monday, July 19 2010 at 5:46 AM

12. brian atwood maniac pumps the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. These Brian Atwood 'Loca' studded pumps are so ravishing, that I'd totally be willing to pop an aspirin before wearing them. And I really lovebrian atwood mesh sandals and Brian Atwood Asymmetric Patent Pumps.brian atwood nude patent leather katie lee pumps. Bold shoes like these sculptural purple suede Brian Atwood 'Lola' pumps make an outfit. purple suede Brian Atwood 'Lola' pumpswith a heel that measures approximately 140mm / 5.5 inches with a 30mm / 1 inch concealed platform. Brian Atwood pumps have a closed toe, cutout detail at arch with elasticated straps and a leather sole.
Herve Leger Dress shop specialises in superior Herve Leger Dress, provides hundreds of discount and fashion Herve Leger Dress, sexy Herve Leger Dress, Herve Leger Skirt, disount Herve Leger Dress-a professional Herve Leger Shop.

# Posted By Brian Atwood maniac pumps on Saturday, August 28 2010 at 2:53 AM

13.
Wonderful brian atwood shoes for your style.BRIAN ATWOOD High-heeled sandals Purple is in stock in our store only one size in 36.5 EU. Elegant purple color, you will like it.
And these Pink Brian Atwood Maniac Patent Platform Pumps not only romantic and gorgeous too! It's patent leather leave us sunshine warmness and sexy!
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
I really love brian atwood nico patent pump.
And this year, brian atwood maniac pumps are so hot among stars, I saw many times that Victoria-Beckham wearing them on the show time.
If you don’t know about brian atwood…You should. When everyone else is obsessing over the latest pair of Loubs or YS’L’s it’s very easy to overlook awesome shoe lines and designers who push the envelope. brian atwood is one of those designers.I’m a fan of his lines because Atwood really sets out to make his shoes a conversation piece. The use of alternative textures and fabrics makes brian atwood shoes unique. When wearing his shoes you are guaranteed a compliment from someone and a definate shoe in for best footwear. So ladies (and gents) get into these! And I know my card carrying “Shoe Wh*res” are going to love these!
Buy brian atwood shoes at http://www.brianatwoodcom.com. Buy brian atwood pumps at http://www.brianatwoodcom.com/brian-atwood-brian-atwood-pumps-c-65_67.html.
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood lexia is worth the investment.
Back by popular demand... brian atwood maniac tan, the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. In a beautiful, very neutral nude tan.
brian atwood whip snake shoe with Exotic whipsnake hidden platform and back metal inset.
Take a walk on the wild side with Atwood Jagger printed knee-high boots. Style them knee high to add sass to an LBD or wear them with the fold-over flap turned up to work this season's hot over-the-knee trend.
brian atwood cage peep Price: $228. 140mm Covered heel. Rounded peep toe. 40mm covered platform. Interwoven cut outs around front. Ankle strap with adjustable metal buckle. Leather insole and lining. Leather sole. Made in Italy.
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood crystal court shoe is worth the investment.
Brian Atwood Platform Chain Pumps with A silver chain scales the lace-up back of this vamped-up pumps.
brian atwood snakeskin platforms is the classic and the elastic heel detail was used again from last Fall.
brian atwood patent leather and mesh Futuristic patent leather style with mesh details and contrast stitching.
Heel measures approximately 95mm/ 3.5 inches. Let your feet do the talking in brian atwood dorota shoes. Wear this chic style with off-duty denim or to liven up office looks.

# Posted By Brian Atwood loca studded pumps on Saturday, August 28 2010 at 2:58 AM

14. A grand wedding on the beach may be the common dream of most single girls. The bright sunshine, the blue sky and the open sea can satisfy all the demands of the romantic girls. Of course, everything will be perfect with a beach wedding dresses.
Every woman deserve the most beautiful wedding dresses at her special day!The most beautiful smile in the word is belong to the brides when she find her wedding dresses!Love is the time when you slows down in front of the shops selling wedding dresses.
Make the day of your engagement a special one with a A-line or princess wedding dresses!Step like a goddess in tea- length ball gowns,formal ball gowns,victorian ball gowns,debutante ball gowns,prom ball gowns, contemporary ball gownsand vintage ball gowns available in chiffon, organza, silk and satin only at weddingdressesnow.com.
Congratulations! Your little daughter is getting married! But being the mother of the bride (or MOB) is not an easy role. Once upon a time mothers of the bride did most of the wedding planning, and thus got to have their own dreams realized. First of all, choose one from the perfect mother of the bride dresses for yourself here and to be the most elegant mother of bride!
Flower girl dresses must be the perfect accessory for the bride's dress. The flower girls look like the bells ring in the wedding announcements as they toll down the aisle one by one or hand in hand. If you are having flower girls at your wedding, take a look at these beautiful selection of Flower girl dresses from http://www.weddingdressesin.com.

# Posted By A line wedding dresses on Saturday, August 28 2010 at 3:00 AM

15. Negative ions and infrared heating technology with the latest, you can be sure that the company green ghd straighteners is your best new ghd styler. Negative ions to help block the hair cuticle, keeping moisture and prevent heat damage. Infrared is useful to penetrate the hair shaft, in fact, from inside to outside, which means your hair will stay straight and long straight. On top of all this, GHD IV Stylecompany, far more than most irons, hair and production efficiency have higher levels of infrared and negative ions help to keep your hair smooth and shiny.

# Posted By nan on Saturday, August 28 2010 at 3:35 AM

16. authentic nfl jerseyswas engineered and constructed to show the individual team new nfl jerseysand skill position utilizing similar fabrics and applications from the Pro Cut version. Sewn on front, back and TV player numbers, arizona cardinals jersey on a sewn down name plate and team name or logo on front chest or sleeves, where applicable.

# Posted By sasa on Saturday, August 28 2010 at 3:36 AM

17. linda
Gucci Designer handbags are not rightful simple leather lacoste Gucci Outlet men embroidered carrier items imperative for the jurisdiction of girlie items drink in toiletries, make-up and authorize UGG Boots. No girlfriend! An authentic designer MBT Shoes speaks volumes about you and implies that you are a witch of style, seasoning and UGG Boot. However, you power serve as assurance that having an authentic nike dunk is facade your carry through. You Cheap Gucci substitute wonderment if you passion to crack into MBT Discount savvy a blasting move shift you have your pocket dunk shoes and house till you dispatch to that unknown pace when you be credulous saved enough to buy your confess authentic designer bag.

# Posted By Gucci Outlet on Monday, August 30 2010 at 8:58 AM

18. Customize the way generators work wow that going to be a hell of a thing....

# Posted By Computer recycling Houston on Monday, August 30 2010 at 6:35 PM

19. But, jewelers pandora jewelry use bold-colored gemstones buy Pandora such as ruby, emerald, sapphire, Pandora Bangles turquoise and coral to add drama to the jewelryThe Beads Bangles term 'Art Deco' was coined from a title Pandora Bangles Sale used in an exposition in'25 Pandora bracelets by La Socit des artistes dcorateurs Pandora bracelet , a popular international art design Beads bracelets movement during'20s. In'25, the society organized buy pandora bracelets Exposition Internationale des Arts Dcoratifs et Industriels Modernes.

# Posted By pandora bracelets on Tuesday, August 31 2010 at 5:19 AM

20. Rails 3 would be a super duper hit


Houston Electrician

# Posted By Houston Electrician on Tuesday, August 31 2010 at 4:25 PM

21. Couldn't agree more...Had a post already written about this too, (good job i checked around first)never mind.It is a really good tune though.
Here's hoping more labels wise up and do this.

# Posted By cheap jerseys on Wednesday, September 1 2010 at 2:15 AM

22.
Epayebuy provide a wide range of nfl jerseys. we are finally nfl jerseys outlet here to offer you the easiest way to nfl jerseys discount customize and purchase your cheap discounted nfl jerseys at the lowest price in market. Also,we offer other variety of team jerseys ranging from cheap nhl jerseys to mlb jerseys. nhl shop online is so easy way to suport your nhl team.

# Posted By fewrewree on Wednesday, September 1 2010 at 7:14 PM

23. Are you always vexed about herve leger wearing what kind of dress at a banquet?
Herve Leger bandage dress online store eliminates Christian Louboutin your worries.
Ladies who is beautiful and noble may choose Herve Leger bandage
dress. The herve leger bandage dress dress highlights your perfect feminine body curve.
If you wear this dress, it will send out your inherent Hermes Handbag glamour.
It is specially designed for you and meets your noble Moncler taste.
Wherever you go, you will be the focus. If you haven't a suitable
dress to attend a banquet and want to buy herve leger dresses one now, Herve Leger bandage
dress online store is your best choice.

# Posted By Herve Leger on Thursday, September 2 2010 at 1:45 AM

24. As we all know that high-heel shoes are the favorites of female stars. And recently, the latest styles aroused their great interests.
Monclerdonna There is no doubt that Christian Louboutin red outsole’s shoes enjoy a leading position. Its fans include Angelina Jolie, Sarah Jessica Parker,
Moncleruomo Victoria Beckham and so on. Surely, a pair of delicate and comfortable high-heel shoe is every woman’s wise choice. After all, the pump can not only make you look taller, but also your good taste can be expressed completely.

# Posted By moncler on Thursday, September 2 2010 at 3:12 AM

Add a Comment

(If you leave this blank, your IP address will be displayed instead)

(Optional, will not be displayed on the site)