This article briefly talks about how to write a mountable rails gem and what are the practices that I followed
First things first
Rails generates nice boilerplate for your gem which is sometimes hard to get it right in the first go. Use this simple command and you are good to go
- The
--mountable
option helps in creating a mountable gem. - The
--skip-test-unit
skips generation of test templates intest
folder - The
--dummy-path
specifies where the dummy test application (which we will be using for testing) should be generated. It is usually created intest
folder but you want that to be created inspec
folder so that you can use rspec
Importance of dummy app
Some of the gems that you develop which depend on rails need to run specs in rails environment. Since gem doesn't have a rails env, it uses dummy app's rails env to run such tests. This is useful when you write specs for controllers, helpers etc.
When you set up rspec by adding rspec-rails
to your Gemfile
, you need to add
these lines at the top of spec_helper.rb
so that rspec loads rails env of dummy
app.
General flow of development
-
Never checkin
Gemfile.lock
in your git repository{or whatever SCM that you are using}
-
First, add all the dependent gems that your gem needs in Gemfile and develop your gem.
-
Once you have finalized your dependent gems, move those gem declarations to
gemspec
file. Add all dependent gems withadd_dependency
method and add all development dependent gems withadd_development_dependency
method -
Its important to note that you should require your dependent gems explicitly in the root file of your gem. Say if your gem is named
my_cool_gem
, then you should havemy_cool_gem.rb
created insidelib
folder. If your gem is dependent onstrong_parameters
, then you need to add these lines: