2011-08-03 2 views
0

私はBillオブジェクトを取得してテストを実行しようとしています。これは米国議会の法案であり、データディレクトリにrsyncを介してxmlで持っています。私のコードでは、 "h1.xml"というように、xmlを解析してwww.govtrack.usから請求書の全文を取得します。だから、私のメインアプリで、法案apiの更新を必要とするオブジェクトを含むRailsテスト

  • を作成する
 
    def self.update_from_directory 
    Dir.glob("#{Rails.root}/data/bills/small_set/*.xml").each do |bill_path| 
     bill_name = bill_path.match(/.*\/(.*).xml$/)[1] 
     b = Bill.find_or_create_by(:govtrack_name => bill_name) 
     b.update_bill 
     b.save! 
    end 
    end 
  • 更新法案を(メソッドのデフself.update_from_directoryにグロブ経由)法案名(例えばH1)を取得します
 
def update_bill 
    file_data = File.new("#{Rails.root}/data/bills/#{self.govtrack_name}.xml", 'r') 
    bill = Feedzirra::Parser::GovTrackBill.parse(file_data) 
    if bill && (self.introduced_date.nil? || (bill.introduced_date.to_date > self.introduced_date)) 

     self.congress = bill.congress 
     self.bill_type = bill.bill_type 
     self.bill_number = bill.bill_number 
     ... and so on . . . until: 
     get_bill_text 
  • 更新法案のテキスト
 
    def get_bill_text 
     bill_object = HTTParty.get("#{GOVTRACK_URL}data/us/bills.text/#{self.congress.to_s}/#{self.bill_type}/#{self.bill_type + self.bill_number.to_s}.html") 
     self.bill_html = bill_object.response.body 
     self.text_updated_on = Date.today 
     Rails.logger.info "Updated Bill Text for #{self.ident}" 
    end 

と法案レコードが私の目標は、私はテストのために全体の法案をモックとしたい、非常に簡単です:

 
    def setup 
     @my_test_bill = Bill.new(:govtrack_id => "h1") 
     @my_test_bill.update_bill 
    end 

私はwebmockやビデオデッキ作業を取得しようとしています、私が見つけることができるすべての例は、特定の呼び出しを模擬する方法を提供し、私は全く新しいupdate_billメソッドを再入力する必要はありません。

どのような考えにも大変感謝しています。

ティム

答えて

1

にごupdate_bill方法の変更を検討:その後のセットアップ方法に変更

def update_bill 
    file_data = File.new("#{Rails.root}/data/bills/#{self.govtrack_name}.xml", 'r') 
    bill = Feedzirra::Parser::GovTrackBill.parse(file_data) 
    if bill && (self.introduced_date.nil? || (bill.introduced_date.to_date > self.introduced_date)) 

    self.congress = bill.congress 
    self.bill_type = bill.bill_type 
    self.bill_number = bill.bill_number 

    # Yield to a block that can perform arbitrary calls on this bill 
    if block_given? 
    yield(self) 
    end 

    # Fill bill text if empty 
    if bill_html.blank? && text_updated_on.blank? 
    get_bill_text 
    end 
end 

:正確に解決策ではないかもしれない

def setup 
    @my_test_bill = Bill.new(:govtrack_id => "h1") 
    @my_test_bill.update_bill do |bill| 
    bill.text_updated_on = Date.today 
    bill.bill_html = "The mock bill contents" 
    end 
end 

を、しかし、この種のアプローチ - レシーバをメソッドに与えられたブロックに戻すことで、実行時に特定のメソッドの正確な動作を変更することができます。

関連する問題