Reputation: 2503
I am a complete Ruby newby and am playing around with rspec
I am testing a class (Account) that has this line:
attr_reader :balance
When I try to test it with this method:
it "should deposit twice" do
@acc.deposit(75)
expect {
@acc.deposit(50)
}.to change(Account.balance).to(125)
end
I get this error:
NoMethodError in 'Account should deposit twice'
undefined method `balance' for Account:Class
I don't understand why I get the error since the attribute 'balance' exists, however I can see that it is not a method, but shouldn't rspec be able to find it anyway?
Update: As Jason noted I should be @acc.balance, since this is what I am asserting. But I get 'nil is not a symbol' when doing this.
Upvotes: 3
Views: 3350
Reputation: 3387
It should be:
it "should deposit twice" do
@acc.deposit(75)
expect {
@acc.deposit(50)
}.to change { @acc.balance }.to(125)
end
Please note that you need use curly braces { ... }
instead of parentheses ( ... )
around @acc.balance
. Otherwise @acc.balance
is evaluated before it is passed to change
method which expects either symbol or block.
Upvotes: 1
Reputation: 14671
i think it should be
expect {@acc.deposit(50)}.to change(@acc.balance}.to(125
)
Upvotes: 1
Reputation: 3766
It should be @acc.balance
it "should deposit twice" do
@acc = Account.new
@acc.deposit(75)
@acc.balance.should == 75
expect {
@acc.deposit(50)
}.to change(@acc, :balance).to(125)
end
Upvotes: 4