Creating a Factory for the Audit Log Using FactoryGirl
Learn how to update the factories to give default test values for the new audit log functionality.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide we are going to create some factories and test cases for our audit log.

If you go to spec/factories, you'll find a file called audit_logs.rb, and there's also a file called audit_log_spec.rb in spec/models. These files were created when we ran the resource generator.

Update the audit_logs.rb factory to look like this:

# spec/factories/audit_logs.rb

FactoryGirl.define do
  factory :audit_log do
    user
    status 0
    start_date (Date.today - 6.days)
    end_date nil
  end
end

Here I've removed the "nil" value and changed the value of status to 0. I've also changed the value for the start_date attribute.

Before we go on, let's see how I came up with the start_date value in the factory. Open up the Rails console and follow along to run these scripts.

Let's say I want the text messages to be sent out on Sunday, the 10th of July, 2016. For this, we want the start date to be the 4th because we want the log to cover everything from the 4th to the 10th. To do that, I think the best way is to subtract six days from today. So, it should be:

Date.today - 6.days

And that's how I came up with what our start_date value should be.

Now let's update the seed file and create a number of audit log records:

# db/seeds.rb

100.times do |audit_log|
  AuditLog.create!(user_id: User.last.id, status: 0, start_date: (Date.today - 6.days))
end

puts "100 audit logs have been created"

Now let's wipe out and refill all of the databases with the db:setup command:

bundle exec rake db:setup

Lastly, open the rails console in the test environment, and check if we can create a factory with the command:

FactoryGirl.create(:audit_log)

And you'll see that this works properly. Nice work, you're ready to move onto the next guide.

Resources