[rspec-users] NOOB question RSPEC

David Chelimsky dchelimsky at gmail.com
Mon May 14 23:02:29 EDT 2007


On 5/14/07, Federico Brubacher <fbrubacher at gmail.com> wrote:
>
> Hi all !!
>
>
> I have this code:
>  require 'account'
>
>
> describe Account, "when first created" do
>    before do
>      @account = Account.new
>    end
>
>
>   it "should have a balance of $0" do
>      @account.balance.should eql(Money.new(0, :dollars))
>    end
>
>
>   after do
>      @account = nil
>    end
>  end
>
>
> How can I pass the @account.balance.should eql(Money.new(0, :dollars))
>  spec. From my understanding you .eql? in ruby is true if the object
>  are the same (reference points to same object) or if one inherits the
> other.

This is only true for certain classes in the Ruby libraries, but not
for the Ruby language. By default, equal?, eql? and even == only
return true for the same Object. Here's evidence:

irb(main):001:0> class Arbitrary
irb(main):002:1> def initialize
irb(main):003:2> @member = 1
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> a = Arbitrary.new
=> #<Arbitrary:0x857b4 @member=1>
irb(main):007:0> a2 = Arbitrary.new
=> #<Arbitrary:0x81b3c @member=1>
irb(main):008:0> a == a2
=> false
irb(main):009:0> a.eql?(a2)
=> false
irb(main):010:0> a.equal?(a2)
=> false
irb(main):011:0> a == a
=> true
irb(main):012:0> a.eql?(a)
=> true
irb(main):013:0> a.equal?(a)
=> true

>
>
> I thought of using this code for Account :
>
> class Account
>   attr_accessor :balance
>   def initialize
>     self.balance = Money.new(0, :dollars)
>   end
> end
>
> class Money < Account
>   attr_accessor :amount, :currency
>   def initialize(amount, currency)
>     @amount = amount
>     @currency = currency
>   end
> end

>From an OO perspective this is probably not what you want. Account and
Money are different concepts and don't belong in any sort of
hierarchical relationship together.

This really is a Ruby question, not an RSpec question. I'd recommend
that you simply override eql? or == (or both) on your Money class. Do
that spec-first separately. Then the example you provided above should
pass.

Please let us know if that works for you.

Cheers,
David

ps - there's no need to have after(:each) { @account = nil }. Each
example gets run in a new instance of Object, so instance variables
are out of scope from example to example.

>
>
>  But still can make it work. It does not pass the spec.
>  Thanks !
> --
> Federico Brubacher
> www.fbrubacher.com
>
> Colonial Duty Free Shop
> www.colonial.com.uy
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>


More information about the rspec-users mailing list