rb,
remove the test_truth method, and add a test_valid one that just takes these two fixtures
and ensures that they are valid:
def test_valid
CHAPTER 5 ?– A DATABASE-DRIVEN SHOP 85
assert customers('cust1').valid?
assert customers('cust2').valid?
end
Go ahead and run the test case now, to see whether it runs:
jruby test/unit/customer_test.rb
In this case there??™s no need to use Rake for testing. You can just run the file you want to
specifically, so you won??™t have to wait for all the other tests to run too. The next point is to
make sure that all those validates_presence_of work as they??™re expected to. So, you create a
new test that sets the sur_name to an empty string, and then to nil, to make sure the preceding
code catches both these cases:
def test_no_sur_name
p = customers('cust1')
p.sur_name = ''
assert !p.valid?
assert p.errors.invalid?(:sur_name)
p.sur_name = nil
assert !p.valid?
assert p.errors.invalid?(:sur_name)
end
Now you could go ahead and write methods like this for the other six required attributes.
But really, isn??™t that overkill? Shouldn??™t there be a better way to achieve this, because the methods
will look exactly like the preceding one? Duplication is always evil, and you should
practice DRY even while writing tests. The dynamic nature of Ruby makes it easy to define
these methods through metaprogramming. So, scratch the test_no_sur_name method and
replace it with this code:
%w(sur_name shipping_address_postal shipping_address_zip
shipping_address_country billing_address_postal
billing_address_zip billing_address_country).
Pages:
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166