The idea is to create a Ruby on Rails application from scratch, that connects with MongoDB. The gems involve are:
- MongoID: To integrate Rails and MongoDB
- Slim: An alternative template engine to ERB (the Rails default one).
- Rspec: A BDD gem to express the tests as specifications
- Cucumber: A BBD gem to express the acceptance tests in Gherkin Syntax
NOTE: You can find the source code for this tutorial here
Technology Stack: MongoDB, Ruby, Rails, GIT (Optional), VIM (Optional)
Create a rails app without active record and test unit
Since we are using MongoDB, a NoSQL database, we don’t need ActiveRecord, so we can use the option
--skip-active-record in order to avoid the creation of all the files and configuration related.
In the same way, we want to use Rspec and Cucumber for automation testing, so we can omit the Unit Test installation as well with the option
Installing MongoID gem
Open the Gemfile and add the dependency
gem “mongoid” and then run
Now any time that you run a generate command that involves models creation it will invoke MongoID instead of ActiveRecord.
NOTE: At the time of writing this blog the lastest release for MongoID (3.0.5) is not compatible with Rails 4, so you have to use the master version instead:
Installing Slim gem
Open the Gemfile and add the gem dependency:
gem “slim-rails” and run
Now any time that you run a generate command that involves template creation it will use Slim instead of ERB.
Installing Rspec gem
One more time we add the dependency:
1 2 3
And then run:
Since we are using MongoID and not ActiveRecord, you need to comment these two lines from spec/spec_helper.rb:
1 2 3 4 5 6 7 8 9 10 11
Installing Cucumber gem
Again we add the dependency:
1 2 3 4
And the command to install it:
Since we are using MongoID and not ActiveRecord, you need to change the database cleaner strategy from transaction to truncation in features/support/env.rb:
Let’s create some entities
To show the impact of these gems in a standar generate command, let see what has changed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
This is the command output, let’s see what has changed from the default one:
- views: We are invoking slim so we are generating slim extension instead of erb.
- db: We are not generating migrations. Since MongoDB is a schemaless database, we don’t need to create tables.
- model: We are invoking mongoid now, so we are creating models prepared to work with Mongo:
1 2 3 4 5 6