diff --git a/lib/recurly/subscription.rb b/lib/recurly/subscription.rb index b38333308..76309966b 100644 --- a/lib/recurly/subscription.rb +++ b/lib/recurly/subscription.rb @@ -2,6 +2,8 @@ module Recurly class Subscription < Resource autoload :AddOns, 'recurly/subscription/add_ons' + class NotPreviewableError < StandardError; end + # @macro [attach] scope # @scope class # @return [Pager] A pager that yields +$1+ subscriptions. @@ -51,6 +53,20 @@ class Subscription < Resource ) alias to_param uuid + def self.preview(attributes = {}) + new(attributes) { |record| record.preview } + end + + def preview + raise NotPreviewableError.new('Cannot preview an existing subscription') unless new_record? + + clear_errors + @response = API.send(:post, "#{path}/preview", to_xml) + reload response + rescue API::UnprocessableEntity => e + apply_errors e + end + # @return [Subscription] A new subscription. def initialize attributes = {} super({ :currency => Recurly.default_currency }.merge attributes) diff --git a/spec/recurly/subscription_spec.rb b/spec/recurly/subscription_spec.rb index 65b49c1c2..451fd7ef1 100644 --- a/spec/recurly/subscription_spec.rb +++ b/spec/recurly/subscription_spec.rb @@ -251,6 +251,16 @@ subscription.invoice.must_equal nil end end + end + + describe 'previewing' do + it 'cannot preview an existing subscription' do + stub_api_request :get, 'subscriptions/abcdef1234567890', 'subscriptions/show-200-noinvoice' + subscription = Subscription.find 'abcdef1234567890' + assert_raises Subscription::NotPreviewableError do + subscription.preview + end + end end end