# How to do unit test whic allows null in the column

**URL:** <https://www.ruby-forum.com/t/how-to-do-unit-test-whic-allows-null-in-the-column/151272>\
**Category:** Rails\
**Created:** [October 19, 2008, 11:28am UTC](https://www.ruby-forum.com/t/how-to-do-unit-test-whic-allows-null-in-the-column/151272 "2008-10-19T11:28:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jicksta](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/7ba0ec/32.png) [@jicksta](https://www.ruby-forum.com/u/jicksta)\
**Post date:** [October 19, 2008, 11:28am UTC](https://www.ruby-forum.com/t/how-to-do-unit-test-whic-allows-null-in-the-column/151272/1 "2008-10-19T11:28:22Z")

</div>

Hi, I have a carts table with columns: campsite, arrival\_date, nights,  
parents, children, family\_claim, total. Here children and family\_claim  
column allows null so even if the value is not passed for these columns  
it should be valid entry. How can I achieve this. At the moment I’m  
using this way in the cart\_test.rb:

def test\_invalid\_with\_empty\_attribute  
cart = Cart.new(:children =\> “”, :family\_claim =\> 1)  
assert !cart.valid?  
assert cart.errors.invalid?(:campsite)  
…  
end

So, I just wan’t to make sure I’m on the right track. Thanks.

---

<div class="post-metadata">

**Author:** ![jicksta](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/7ba0ec/32.png) [@jicksta](https://www.ruby-forum.com/u/jicksta)\
**Post date:** [October 19, 2008, 11:41am UTC](https://www.ruby-forum.com/t/how-to-do-unit-test-whic-allows-null-in-the-column/151272/2 "2008-10-19T11:41:17Z")

</div>

Hi Jay,

I quite like this way of working its nice and clean and each test  
demonstrates exactly what you expect to be invalid and why

def setup  
@va.lid\_attributes = {  
:parents =\> 1  
:children =\> 1,  
:family\_clam =\> 1,  
:campsite =\> ‘blah’,  
:total =\> 100,  
}  
end

def test\_valid  
cart = Cart.create(@valid\_attributes)  
assert cart.valid?  
end

def test\_valid\_if\_children\_is\_nil  
cart = Cart.create(@valid\_attributes.merge(:children =\> nil)  
assert cart.valid?

# or

assert cart.errors.on(:children).nil?  
end

def test\_invalid\_if\_total\_is\_nil  
cart = Cart.create(@valid\_attributes.merge(:total =\> nil)  
assert ! cart.valid?  
assert cart.errors.on(:total)  
end

I hope this helps.

RobL

---

<div class="post-metadata">

**Author:** ![jicksta](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/7ba0ec/32.png) [@jicksta](https://www.ruby-forum.com/u/jicksta)\
**Post date:** [October 19, 2008, 1:24pm UTC](https://www.ruby-forum.com/t/how-to-do-unit-test-whic-allows-null-in-the-column/151272/3 "2008-10-19T13:24:19Z")

</div>

> I hope this helps.
> 
> RobL

Thanks RobL. It sure did help…
