0
votes

I'm having trouble getting rspec to properly test an Active Record callback. In my model I have:

after_create :check_twitter_limit,   if: Proc.new { |row| row.service == "twitter" }

Where service is the social media site being saved to the db. In essence, if the event is a twitter event, let's check the rate limit.

The method looks like this:

def check_twitter_limit
binding.pry
if EventTracker.within_fifteen_minutes.twitter.size > 12 && EventTracker.within_fifteen_minutes.twitter.size % 3 == 0
  alert_notifier.ping("*[#{user}](#{ANALYTICS_URL}#{distinct_id})* (#{organization}) just _#{event}_ and has made *#{EventTracker.within_fifteen_minutes.twitter.size}* twitter requests in the last 15 minutes!")
end

end

Notice the pry binding. I have this in here as proof that the code works. Every time I run rspec, I get into the pry binding, so I know the method is being called.

Here is the spec:

it "should trigger the twitter alert limit when conditions are met" do  
        expect(EventTracker).to receive(:check_twitter_limit)
  EventTracker.create({
    event:            "Added twitter users to list",
    organization:     "Org",
    user:             "Cool Guy",
    event_time_stamp: Time.now.to_i - 14400,
    distinct_id:      "1",
    media_link:       "http://www.twitter.com",
    is_limited:       true,
    service:          "twitter"
    })

    end

Here is the error:

Failure/Error: expect(EventTracker).to receive(:check_twitter_limit)
   (<EventTracker(id: integer, event: string, organization: string, user: string, event_time_stamp: integer, distinct_id: string, media_link: string, is_limited: boolean, service: string, created_at: datetime, updated_at: datetime) (class)>).check_twitter_limit(any args)
       expected: 1 time with any arguments
       received: 0 times with any arguments

This test fails despite the fact that I know the callback is being triggered when using pry, and I can confirm that the record is being saved to the db.

Any ideas on what is going on?

1

1 Answers

1
votes

I think you want an instance of EventTracker to receive check_twitter_limit, not the class itself. You can do this in RSpec 3.0 with

expect_any_instance_of(EventTracker).to receive(:check_twitter_limit)