Sam Selikoff
Sam Selikoff

Reputation: 12684

Running callbacks in rspec

I have a Reminder model that needs to calculate an important piece of data upon creation. I'm using the before_create callback for this purpose:

class Reminder < ActiveRecord::Base
  validates      :next_send_time, presence: true

  before_create  :set_next_send_time

  def set_next_send_time
    self.next_send_time = calc_next_send_time
  end
end

The problem is, the callback doesn't seem to be running in my controller spec. The attribute is vital to the model and throughout the rest of my application's tests I will expect it to be calculated upon create.

The reminders_controller#create method is

def create
  respond_with Reminder.create(reminder_params)
end

and here's the reminders_controller_spec:

RSpec.describe Api::RemindersController do

  describe 'create' do

    it "should work" do

      post :create,
        reminder: {
          action: 'Call mom',
          frequency: 1,
          type: 'WeeklyReminder',
          day_of_week: 0,
          start_date: Date.new,
          time_of_day: '07:00:00',
          user_id: 1
        },
        format: :json

      reminders = Reminder.all
      expect(reminders.length).to eq(1)
    end

  end
end

If I inspect the response, the error is that next_send_time is null.

How can I get the Reminder's callback to run in my Rspec tests?

Upvotes: 1

Views: 1840

Answers (2)

Jason Axelson
Jason Axelson

Reputation: 4665

If you're using Rails 4.0 you can use the [TestAfterCommit][1] gem.

If you're using Rails 5.0 it is built in: https://github.com/rails/rails/pull/18458

Upvotes: 0

evanbikes
evanbikes

Reputation: 4171

Instead of before_create, try before_validation :set_next_time, on: :create.

If the record doesn't pass validation, the callback wouldn't fire.

EDIT: Corrected the method name to before_validation.

Upvotes: 2

Related Questions