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

class BodyScore < ActiveRecord::Base

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

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

end
4

1 回答 1

0

像这样的东西:

  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

您应该涵盖所有可能的行为。

我还使用了用于测试此处object.send描述的私有方法的技巧。

upd:由于您是测试新手,我将添加一些有关测试的描述。

我使用FactoryGirl来创建新工厂并为此使用简短的语法

我使用let分配新变量而不是before块。

于 2012-12-23T11:30:49.530 回答