2012-12-23 36 views
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 

如何为reject_body_scores(归因)方法编写测试代码?

class BodyScore < ActiveRecord::Base 

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

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

end 

回答

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块。

+0

感谢您的回复。我在编写测试代码方面很新,所以这帮助我更好地理解。 – nbh

相关问题