Browse files

Added should_create and should_destroy [#190 state:resolved]

  • Loading branch information...
1 parent 712a026 commit 673ffa66974502e1f12c70fab32a19dc91d365e1 @jferris jferris committed May 5, 2009
Showing with 104 additions and 0 deletions.
  1. +1 −0 .gitignore
  2. +39 −0 lib/shoulda/macros.rb
  3. +64 −0 test/other/helpers_test.rb
View
1 .gitignore
@@ -4,3 +4,4 @@ coverage
.svn/
pkg
*.swp
+tags
View
39 lib/shoulda/macros.rb
@@ -65,8 +65,47 @@ def should_not_change(expression)
end
end
+ # Macro that creates a test asserting that a record of the given class was
+ # created.
+ #
+ # Example:
+ #
+ # context "creating a post" do
+ # setup { Post.create(post_attributes) }
+ # should_create :post
+ # end
+ def should_create(class_name)
+ should_change_record_count_of(class_name, 1, 'create')
+ end
+
+ # Macro that creates a test asserting that a record of the given class was
+ # destroyed.
+ #
+ # Example:
+ #
+ # context "destroying a post" do
+ # setup { Post.first.destroy }
+ # should_destroy :post
+ # end
+ def should_destroy(class_name)
+ should_change_record_count_of(class_name, -1, 'destroy')
+ end
+
private
+ def should_change_record_count_of(class_name, amount, action) # :nodoc:
+ klass = class_name.to_s.camelize.constantize
+ before = lambda do
+ @_before_change_record_count = klass.count
+ end
+ human_name = class_name.to_s.humanize.downcase
+ should "#{action} a #{human_name}", :before => before do
+ assert_equal @_before_change_record_count + amount,
+ klass.count,
+ "Expected to #{action} a #{human_name}"
+ end
+ end
+
include Shoulda::Private
end
end
View
64 test/other/helpers_test.rb
@@ -238,4 +238,68 @@ class HelpersTest < Test::Unit::TestCase # :nodoc:
end
end
end
+
+ context "given one treat exists and one post exists" do
+ setup do
+ Treat.create!
+ Post.create!(:title => 'title', :body => 'body', :user_id => 1)
+ end
+
+ teardown do
+ Treat.delete_all
+ Post.delete_all
+ end
+
+ context "creating a treat" do
+ setup do
+ Treat.create!
+ end
+
+ should_create :treat
+ should_fail do
+ should_create :post
+ end
+ end
+
+ context "creating a treat and a post" do
+ setup do
+ Treat.create!
+ Post.create!(:title => 'title 2', :body => 'body', :user_id => 1)
+ end
+
+ should_create :treat
+ should_create :post
+ end
+
+ context "destroying a treat" do
+ setup do
+ Treat.first.destroy
+ end
+
+ should_destroy :treat
+ should_fail do
+ should_destroy :post
+ end
+ end
+
+ context "destroying a treat and a post" do
+ setup do
+ Treat.first.destroy
+ Post.first.destroy
+ end
+
+ should_destroy :treat
+ should_destroy :post
+ end
+
+ context "doing nothing" do
+ should_fail do
+ should_create :treat
+ end
+
+ should_fail do
+ should_destroy :treat
+ end
+ end
+ end
end

0 comments on commit 673ffa6

Please sign in to comment.