Rspec expects throws "undefined method"

I'm full Ruby newby and play with rspec

I am testing a class (Account) that has the following line:

attr_reader :balance

When I try to check 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 am getting an error, because there is an attribute “balance”, however I see that this is not a method, but should rspec not find it anyway?

Update: As Jason noted, I have to be @ acc.balance, as that is what I am claiming. But I do it "nil is not a symbol."

+3
source share
3 answers

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
+4
source

I think it should be

expect {@acc.deposit(50)}.to change(@acc.balance}.to(125)

+1
source

:

it "should deposit twice" do
  @acc.deposit(75)
  expect {
    @acc.deposit(50)
   }.to change { @acc.balance }.to(125)
end

Note that you need to use curly braces { ... }instead of parentheses ( ... )around @acc.balance. Otherwise, it @acc.balanceis evaluated before a method is passed changethat expects either a character or a block.

+1
source

Source: https://habr.com/ru/post/1759002/


All Articles