# Attachment\_fu, how would you test this?

**URL:** <https://www.ruby-forum.com/t/attachment-fu-how-would-you-test-this/137884>\
**Category:** Rails\
**Created:** [May 17, 2008, 4:08pm UTC](https://www.ruby-forum.com/t/attachment-fu-how-would-you-test-this/137884 "2008-05-17T16:08:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![xdmx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/53a042/32.png) [@xdmx](https://www.ruby-forum.com/u/xdmx)\
**Post date:** [May 17, 2008, 4:08pm UTC](https://www.ruby-forum.com/t/attachment-fu-how-would-you-test-this/137884/1 "2008-05-17T16:08:51Z")

</div>

Hi, i’m starting to go nuts because of this. i’m playing with  
attachment\_fu, everything is ok, but i also want to put everything under  
test too. Actually i’ve a post, where you can upload images, and it  
works. But now i want to set that it’s mandatory to upload at least 1  
image.  
The code it’s quite simple and stupid:

errors.add(:image, ‘at least one’) if post.images.size.zero?

…and obviously it works…

…but how would you test this by unit tests?

---

<div class="post-metadata">

**Author:** ![xdmx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/53a042/32.png) [@xdmx](https://www.ruby-forum.com/u/xdmx)\
**Post date:** [May 17, 2008, 4:34pm UTC](https://www.ruby-forum.com/t/attachment-fu-how-would-you-test-this/137884/2 "2008-05-17T16:34:21Z")

</div>

Here’s a rough cut off the top of my head. (I haven’t used Test::Unit  
in a long time; I hope I’m not too rusty).

# using RSpec

describe Post do

it “is invalid without at least one image” do  
post = Post.new  
post.should\_not be\_valid  
end

it “is valid with at least one image” do  
post = Post.new :images =\> [Image.new]  
post.should be\_valid  
end

end

# using Test::Unit

class PostTest \< Test::Unit::TestCase

def test\_invalid\_without\_at\_least\_one\_image  
post = Post.new  
assert !post.valid?  
end

def test\_valid\_with\_at\_least\_one\_image  
post = Post.new :images =\> [Image.new]  
assert post.valid?  
end

end

I assume that you’ve written your own validate method on your model.  
You can also use validates\_length\_of or validates\_size\_of for the  
images association, e.g.,

validates\_length\_of :images, :minimum =\> 1, :message =\> “at least %d”

Regards,  
Craig
