Permalink
Browse files

Add money-rails test helper (rspec matcher)

  • Loading branch information...
1 parent 15dd1f4 commit 8e96efb33205ad5ad6443253009352d93b52dee1 @alup alup committed Dec 19, 2012
Showing with 80 additions and 0 deletions.
  1. +49 −0 lib/money-rails/test_helpers.rb
  2. +31 −0 spec/test_helpers_spec.rb
@@ -0,0 +1,49 @@
+require 'rspec/expectations'
+
+module MoneyRails
+ module TestHelpers
+ extend RSpec::Matchers::DSL
+
+ matcher :monetize do |attr|
+
+ chain(:with_currency) do |currency|
+ @currency_iso = currency
+ end
+
+ chain(:as) do |virt_attr|
+ @as = virt_attr
+ end
+
+ match do |target|
+ matched = true
+ money_attr = @as.presence || attr.to_s.sub(/_cents$/, "")
+ matched = false unless target.send(money_attr).instance_of? Money
+ if @currency_iso
+ matched = false unless target.send(money_attr.to_sym).currency.id == @currency_iso
+ end
+ matched
+ end
+
+ description do
+ description = "monetize #{expected}"
+ description << " as #{@as}" if @as
+ description << " with currency #{@currency_iso}" if @currency_iso
+ description
+ end
+
+ failure_message_for_should do |actual|
+ msg = "expected that #{actual} would be monetized"
+ msg << " as #{@as}" if @as
+ msg << " with currency #{@currency_iso}" if @currency_iso
+ msg
+ end
+
+ failure_message_for_should_not do |actual|
+ msg = "expected that #{actual} would not be monetized"
+ msg << " as #{@as}" if @as
+ msg << " with currency #{@currency_iso}" if @currency_iso
+ msg
+ end
+ end
+ end
+end
@@ -0,0 +1,31 @@
+# -*- encoding : utf-8 -*-
+require 'spec_helper'
+
+if defined? ActiveRecord
+ describe 'TestHelpers' do
+
+ require "money-rails/test_helpers"
+ include MoneyRails::TestHelpers
+
+ let(:product) do
+ Product.create(:price_cents => 3000, :discount => 150,
+ :bonus_cents => 200, :optional_price => 100,
+ :sale_price_amount => 1200)
+ end
+
+ describe "monetize matcher" do
+
+ it "matches model attribute without a '_cents' suffix by default" do
+ monetize(:price_cents).should be_true
+ end
+
+ it "matches model attribute specified by :as chain" do
+ monetize(:price_cents).as(:discount_value).should be_true
+ end
+
+ it "matches model attribute with currency specified by :with_currency chain" do
+ monetize(:price_cents).with_currency(:gbp).should be_true
+ end
+ end
+ end
+end

0 comments on commit 8e96efb

Please sign in to comment.