27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Behavior-driven development<br />

Now when you run this feature, it’ll tell you there’s an undefined method balance,<br />

but didn’t you just define that?<br />

When I take out 10<br />

undefined method `balance' for # (NoMethodError)<br />

Actually, the method you defined was balance= (with an equals sign), which is a setter<br />

method. balance (without an equals sign) in this example is a getter method, which is<br />

used for retrieving the variable you set in the setter method. Not all methods without<br />

equal signs are getter methods, however. To define this method, switch back into lib/<br />

account.rb and add this new method directly under the setter method, as shown in the<br />

following listing.<br />

Listing 2.30 accounts/lib/account.rb<br />

def balance=(amount)<br />

@balance = amount<br />

end<br />

def balance<br />

@balance<br />

end<br />

Here you define the balance= and balance methods you need. The first method is a<br />

setter method, which is used to set the @balance instance variable on an Account object<br />

to a specified value. The balance method returns that specific balance. When you run<br />

this feature again, you’ll see a new error:<br />

When I take out 10<br />

String can't be coerced into Fixnum (TypeError)<br />

./features/step_definitions/account_steps.rb:10:in `-'<br />

This error occurred because you’re not storing the balance as a Fixnum but as a<br />

String. As mentioned earlier, the variable returned from the capture group for the<br />

second step definition is a String. To fix this, you coerce the object into a Fixnum by<br />

calling to_i 8 inside the setter method, as shown in the following listing.<br />

Listing 2.31 accounts/lib/account.rb<br />

def balance=(amount)<br />

@balance = amount.to_i<br />

end<br />

Now anything passed to the balance= method will be coerced into an integer. You also<br />

want to ensure that the other value is also a Fixnum. To do this, open features/<br />

step_definitions/account_steps.rb and change the third step to look exactly like the following<br />

listing.<br />

8 For the sake of simplicity, we use to_i. Some will argue that to_f (converting to a floating-point number) is<br />

better to use for money. They’d be right. This is not a real-world system, only a contrived example. Chill.<br />

41

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!