Reputation: 3285
The purpose of this code is to send an email to a user with an array of products whose discount percentages have reached a given threshold. The products are returned by:
user.notifications
which returns an array of 2 element arrays with the following format:
[[product, notification]]
A notification is an object composed of a discount percentage and a product_id.
send_notification?
checks to see if a user has been sent a notification in the last 7 days and returns a boolean (true if they have not received an email in the last week and false if they have for the product being passed in.)
I have the following job and accompanying test:
class ProductNotificationEmailJob
include SuckerPunch::Job
def perform(user)
user_notifications = user.notifications || []
products = []
notifications = []
user_notifications.each do |notification|
if notification[1].send_notification?
products << notification[0]
notifications << notification[1]
end
end
NotificationMailer.notification_email(user, products).deliver
notifications.each do |notification|
notification.update(notification_date: Time.now)
end
end
end
test:
require 'rails_helper'
describe ProductNotificationEmailJob do
it 'performs' do
notification = ObjectCreation.create_notification
expect(notification.notification_date).to be_nil
user = notification.user
stub = double("Object")
expect(NotificationMailer).to receive(:notification_email).with(user, [notification.my_product.product]).and_return(stub)
expect(stub).to receive(:deliver)
ProductNotificationEmailJob.new.perform(user)
expect(MyProductsNotification.last.notification_date).to_not be_nil
end
end
When I take out the line: include SuckerPunch::Job the test passes fine but I cannot get it to pass with that line in though. For some reason with the include SuckerPunch::Job line it seems as though the object creation method does not work and returns nil for all values. I apologize in advance if I didn't give enough detail but I didn't want to post too much code. Leave a comment and I will include any details requested. Thank you for your time I really appreciate it!
Upvotes: 1
Views: 334
Reputation: 3285
After looking at the problem with fresh eyes I realized I was violating encapsulation rules by even trying to do all of that stuff in the ProductNotificationEmailJob class. I extracted into another class and everything runs fine and is perfectly testable.
Upvotes: 0