0
class Horse < ActiveRecord::Base

  attr_accessible :body_scores_attributes

  has_many :body_scores, :dependent => :destroy

  accepts_nested_attributes_for :body_scores, :reject_if => :reject_body_scores

  private
  def reject_body_scores(attributed)

    new_record? || attributed['date'].blank? || attributed['score'].blank?
  end

end

and

class BodyScore < ActiveRecord::Base

  attr_accessible :horse_id, :score, :scoring_date
  belongs_to :horse

  validates :horse_id, :score, :scoring_date, :presence => true

end
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
nbh
  • 11
  • 4

1 Answers1

0

Something like that:

  describe "#reject_body_scores" do
    context "when record is new" do
      let(:horse) { build :horse }
      let(:options) { {} }
      it "reject body" do
        horse.send(:reject_body_scores, options).should be_true
      end
    end

    context "when date blank" do
      let(:horse) { create :horse }
      let(:options) { {} }
      it "reject body" do
        horse.send(:reject_body_scores, options).should be_true
      end
    end

    context "when score blank" do
      let(:horse) { create :horse }
      let(:options) { { "date" => Date.current } }
      it "reject body" do
        horse.send(:reject_body_scores, options).should be_true
      end
    end

    context "when date and score present" do
      let(:horse) { create :horse }
      let(:options) { { "date" => Date.current, "score" => 5 } }
      it "don't reject body" do
        horse.send(:reject_body_scores, options).should be_false
      end
    end
  end

You should cover all possible behaviors.

I've also used the trick using object.send for testing private methods described here.

upd: Since you new to testing I'll add some description about testing.

I've use FactoryGirl for creating new factories and use short syntax for that.

I've use let to assign new variables instead of before block.

Community
  • 1
  • 1
ck3g
  • 5,829
  • 3
  • 32
  • 52
  • Thanks for the reply. I am new in writing test codes, so this has helped me a lot to understand better. – nbh Dec 23 '12 at 11:47