assert_incremented_by test helpers

I wrote these test_helper methods after being inspired by Zack Chandler’s assert_toggled method


  def assert_incremented_by( number, object, method, *args )
    initial_value = object.send(method, *args)
    yield
    object.reload if object.respond_to? :reload
    assert_equal initial_value + number, object.send(method, *args)
  end  

  def assert_decremented_by( number, object, method, *args, &block )
    assert_incremented_by -number, object, method, *args, &block
  end  

  def assert_no_change_in( object, method, *args )
    initial_value = object.send(method, *args)
    yield
    object.reload if object.respond_to? :reload
    assert_equal initial_value, object.send(method, *args)
  end  


example usage:

  def test_ajax_create_network__for_city_is_successful_and_updates_form_id_value
    assert_incremented_by 1, City, :count do
      xhr :post, :ajax_create_network, :type => 'City', :object => { :name => 'Dummy', :state => 'CA' }
    end
    assert_response :success
    assert_match /\.value='\d+'/, @response.body
  end

...

  def test_after_create__watchlist_notification_on_posting
    assert users(:david).watchlist_companies.include?( companies(:HP) )
    assert_incremented_by 1, WatchlistNotification, :count, :conditions => {:kind => 'posting_commented'} do
      postings(:rodney_HP).comments.create!( :body => 'booyashaka!', :user => users(:greg) )
    end  
  end

  def test_after_create__watchlist_notification__doesnt_happen_on_profile
    assert users(:david).watchlist_companies.include?( companies(:HP) )
    assert_no_change_in WatchlistNotification, :count do
      users(:rodney).profile.comments.create!( :body => 'booyashaka!', :user => users(:greg) )
    end  
  end


Leave a Reply