jorgemanrubia / mailgun_rails

Rails Action Mailer adapter for Mailgun
MIT License
210 stars 70 forks source link

mocking response from mailgun in my rspec test suite #47

Open ygamretuta opened 9 years ago

ygamretuta commented 9 years ago

given:

# app/models/user.rb
def send_daily_request
    self.team_members.each do |member|
      if member.email != self.email
        mail = UserMailer.daily_request(self, member)
        #mail.mailgun_special_variables = {deliverytime:Util.send_question_time(self.timezone, self.daily_update_time)}
        mail.deliver_now
        response = mail.mailgun_api_response

        if response.present?
          save_outgoing(member, response["id"])
          true
        else
          false
        end
      end
    end
  end

...

def save_outgoing(member, message_id)
    message = member.messages.create
    message.build_out_going_message(question:member.user.question)
    message.message_id = message_id
    message.save
  end

which is tested with:

describe 'send_question' do
    it 'saves outgoing message' do
      user = FactoryGirl.create(:team_admin)

      #2 because members include the team admin
      expect{user.send_daily_request}.to change(Message, :count).by(3)
    end
  end

and the forked code retrieving the response from mailgun:

def deliver!(rails_message)
      response = mailgun_client.send_message build_mailgun_message_for(rails_message)
      rails_message.mailgun_api_response = JSON.parse response

      rails_message
    end

how do I test this properly? It seems like my test cannot properly retrieve the response from Mailgun (this works when not on test). Should I use VCR gem for this? or maybe mock the response from Mailgun?