- Read Tutorial
If you're already familiar with using the FactoryGirl Rails gem you will be able to breeze through this section. We'll eventually get into creating mocks and stubs for our microservice, however for right now we're simply going to create some basic objects using factory girl factories. You can also use my FactoryGirl Rails Tutorial for an in depth reference at any point.
Implementing factories for a microservice
In the last section when we implemented RSpec and the other testing gems we also included FactoryGirl. The
factory-girl-rails gem that we're using has a nice built in hook that automatically creates basic factories for us whenever we run generators. So if you look in the
spec/factories/notifications.rb file you'll see that we have a basic set of attributes already setup, let's update this file and add in a second factory so we'll have multiple objects that we can work with in our specs:
# spec/factories/notifications.rb FactoryGirl.define do factory :notification do phone "5555555555" body "My message" source_app "some_app" end factory :second_notification, class: 'Notification' do phone "5555555555" body "My message" source_app "some_app" end end
We can test this out a few ways, first let's startup the rails console in
test mode by running:
rails c -e test
Now we can run:
As you can see this works and gives us the following output:
So now let's refactor our spec from the last section, open up the model spec file for notifications:
# spec/models/notification_spec.rb require 'rails_helper' RSpec.describe Notification, type: :model do describe 'creation' do it 'can be created' do notification = FactoryGirl.create(:notification) expect(notification).to be_valid end end end
Isn't that a much cleaner syntax? If you run the specs now you'll see that they're still passing and now we'll be able to use factories in the future to make test object creation more straightforward.
In the next few sections walk through how to build out our core microservice functionality using BDD.