On Mon, Mar 17, 2008 at 5:53 AM, roberto belardo <[EMAIL PROTECTED]> wrote:
> Hi all,
>  i'm learning rspec and i must admit i really love it.
>  But at the time i started learning it, i already
>  developed my models classes and their callbacks.
>
>  Now i'm trying to get a 100% coverage of my code but i
>  cannot reach it because i do not understand how to
>  spec my callbacks.
>
>  Look at this for example:
>
>  ----------------- User Model
>
>  class User < ActiveRecord::Base
>   before_destroy :delete_associated_comments
>   def delete_associated_comments
>     comments = Comment.find_all_by_user_id(self.id)
>     comments.each { |c|
>       c.destroy
>     }
>   end
>  end
>
>  ----------------- User Spec
>
>  describe User, " being deleted" do
>
>   before(:each) do
>   end
>
>   it "should see deleted his own comments" do
>     user = Factory.create_user()
>     comment_1 = Factory.create_comment(:author =>
>  user)
>     comment_2 = Factory.create_comment(:author =>
>  user)
>     user.destroy
>     comment_1.should be nil
>     comment_2.should be nil

This won't work because you already have a handle on each of these
objects. They are likely deleted from the database, but destroying an
object (in AR terms) does not turn an instance of it to nil.

Give this a shot:

  lambda { Comment.find(comment_1.id) }.should
raise_error(ActiveRecord::RecordNotFound)
  lambda { Comment.find(comment_2.id) }.should
raise_error(ActiveRecord::RecordNotFound)

Although generally I prefer to keep only one expectation per example.

HTH,
David


>   end
>
>  end
>
>  ----------------- Factory Module
>
>   def self.create_user(attributes = {})
>     default_attributes = {
>       :first_name => "Foo",
>       :second_name => "Bar",
>       :user_name => "FooBar",
>       :email => "[EMAIL PROTECTED]"
>     }
>     User.create! default_attributes.merge(attributes)
>   end
>
>   def self.create_comment(attributes = {})
>     default_attributes = {
>       :title => "title",
>       :text => "text",
>       :author => create_user
>     }
>     Comment.create!
>  default_attributes.merge(attributes)
>   end
>
>  -----------------
>
>  I imagined a spec like the one above but obviously it
>  doesn't works. :-(
>  I really do no understand how i can spec my callbacks.
>  Could someone help me with this?
>
>  Thanks in advance,
>  Backslas451.
_______________________________________________
rspec-users mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users

Reply via email to