Testing Mailchimp 3.0 and Gibbon 2.x with Rspec

若如初见. 提交于 2019-12-10 15:43:31

问题


I have a rails 4.2 app that has a newsletter signup via MailChimp using the Gibbon gem.

Here is my initializer:

Gibbon::Request.api_key = ENV['MAILCHIMP_API_KEY']
Gibbon::Request.timeout = 15
Gibbon::Request.throws_exceptions = false

Here are the relevant methods in user.rb:

  # returns the mailchimp member if one exists for @user.email
  def mailchimp_user
    gb = Gibbon::Request.new(api_key: ENV['MAILCHIMP_API_KEY'])
    gb.lists(ENV['MAILCHIMP_LIST_ID']).members(Digest::MD5.hexdigest("#{self.email.downcase}")).retrieve
    rescue Gibbon::MailChimpError => e
    return nil, :flash => { error: e.message }
  end

  def mailchimp_member_id
    if self.mailchimp_user.kind_of?(Array)
      return nil
    elsif self.mailchimp_user.kind_of?(Hash)
      self.mailchimp_user["id"]
    end
  end

  # returns the mailChimp status of the user  
  def mailchimp_status
    if self.mailchimp_user.kind_of?(Array)
      return nil
    elsif self.mailchimp_user.kind_of?(Hash)
      self.mailchimp_user["status"]
    end
  end

  # syncs Mailchimp status to EBW, subscribing and unsubscribing users as appropriate. potential MC status includes
  # 'subscribed', 'unsubscribed', 'pending' and 'cleaned'
  def add_to_mailchimp
    gb = Gibbon::Request.new(api_key: ENV['MAILCHIMP_API_KEY'])
    if self.subscribed? # if the user has checked the "subscribed" checkbox
      if self.mailchimp_status.present? # if MailChimp recognizes the email address
        gb.lists(ENV['MAILCHIMP_LIST_ID']).members(Digest::MD5.hexdigest("#{self.email.downcase}")).update(body: { status: "subscribed" }) #subscribe user 
      elsif self.mailchimp_status.nil? # if MailChimp doesn't have a user for the email address
        gb.lists(ENV['MAILCHIMP_LIST_ID']).members.create(body: { # create a MailChimp pending subscriber
          email_address: "#{self.email}",
          status: "pending", # setting this to 'subscribed' will remove double optin
          merge_fields: {FNAME: "#{self.name}"}
          })
      end

  # unsubscribe user if box is unchecked but mailchimp has user as subscribed or pending
    else
      unless self.mailchimp_user.kind_of?(Array)
        gb.lists(ENV['MAILCHIMP_LIST_ID']).members(self.mailchimp_member_id).update(body: { status: "unsubscribed" })  
      end
    end
  end

I am still learning Rspec, and having trouble applying it in the context of Gibbon::MailChimp. I want to test that subscribing, unsubscribing works as expected for users based on their current status. e.g. users who have unsubscribed are treated differently than new subscribers whose subscriptions on MailChimp need to be created.

来源:https://stackoverflow.com/questions/32528415/testing-mailchimp-3-0-and-gibbon-2-x-with-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!