【问题标题】:How can I write a test code for reject_body_scores(attributed) method?如何为 reject_body_scores(attributed) 方法编写测试代码?
【发布时间】:2012-12-23 09:46:13
【问题描述】:
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

【问题讨论】:

    标签: unit-testing rspec


    【解决方案1】:

    类似的东西:

      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 描述的私有方法。

    更新: 由于您是测试新手,我将添加一些有关测试的说明。

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

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

    【讨论】:

    • 感谢您的回复。我是编写测试代码的新手,所以这对我更好地理解有很大帮助。
    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    相关资源
    最近更新 更多