[rspec-users] [Newbie''s Doubt] Model''s Tests

Lenny Marks
Wed, 18 Apr 2012 01:33:57 -0000

On Apr 17, 2012, at 8:50 PM, Luciano Borges wrote:

> I''m studying Rspec and doing some model''s tests.
>
> I have a table with a field which must have two characters, the field
should not be empty and can not be repeated.
>
> My doubts is with #.
>
> describe State do
>   context "validations" do
>
>     it "The abbreviation should not be empty" do
>       subject.abbreviation = nil
>       subject.should_not be_valid
>     end
>
>     # I can do like example below or I have to break in parts?
>
>     it "The abbreviation  should have 2 characters" do
>       subject.abbreviation = "BA"
>       subject.should be_valid
>
>       subject.abbreviation = "B"
>       subject.should_not be_valid
>
>       subject.abbreviation = "BAA"
>       subject.should_not be_valid
>     end
>
>     it "The abbreviation can not be repeated" do
>
>      # I don''t know how to do!
>
>     end
>   end
> end

With things like the above, I usually want the rule, followed by some examples.
I usually approach like below. Its nice to have it all right in the specdoc.

describe ''validations'' do
   ....
   describe ''abbreviation'', ''must be two unique
characters'' do
       specify ''AB is valid'' do
         subject.abbreviation = ''AB''
         subject.should be_valid
       end

       specify ''A is not valid'' do
         subject.abbreviation = ''A''
         subject.should_not be_valid
       end

      specify ''BAA is not valid'' do
        subject.abbreviation = ''BAA''
        subject.should_not be_valid
      end

I think it would be overkill for the above, but sometimes if I''m
throwing lots of examples at something (e.g. email address validation),
I''ll use a macro like below.

 describe ''abbreviation'', ''must be two unique
characters'' do
      def self.it_is_valid(abbreviation)
         specify "#{abbreviation} is valid" do
           subject.abbreviation = abbreviation
	   subject.should be_valid
         end
      end
      .....
      it_is_valid(''AB'')
      it_is_valid(''BA'')
      it_is_not_valid(''AA'')
      it_is_not_valid(''BAA'')
      .....

-lenny

>
> Thanks,
> Luciano
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL:
<http://rubyforge.org/pipermail/rspec-users/attachments/20120417/a7069bad/attachment.html>