我无法让rspec正确测试Active Record回调。在我的模型中,我有:
after_create :check_twitter_limit, if: Proc.new { |row| row.service == "twitter" }
服务是保存到数据库的社交媒体网站。实质上,如果活动是推特活动,请检查费率限制。
方法如下:
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
端
注意pry绑定。我在这里作为代码工作的证明。每次运行rspec时,我都会进入pry绑定,所以我知道正在调用该方法。
以下是规范:
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
这是错误:
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
尽管我知道在使用pry时触发了回调,但此测试仍然失败,我可以确认记录正在保存到数据库中。
有关正在发生的事情的任何想法?
答案 0 :(得分:1)
我认为您希望EventTracker
的实例接收check_twitter_limit
,而不是类本身。您可以使用
expect_any_instance_of(EventTracker).to receive(:check_twitter_limit)