如何为reject_body_scores(属性)方法编写测试代码?

时间:2012-12-23 09:46:13

标签: unit-testing rspec

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

1 个答案:

答案 0 :(得分: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来测试here所描述的私有方法。

<强> UPD : 由于您刚接触测试,我将添加一些有关测试的说明。

我使用FactoryGirl创建新工厂并使用short syntax

我使用let来分配新变量,而不是before阻止。