[英]Testing dynamically created methods
在我的模型中,我根據數據庫記錄動態創建一些方法:
class Job < ActiveRecord::Base
belongs_to :job_status
# Adds #requisition?, #open?, #paused?, #closed?
class_eval do
JobStatus.all.each do |status|
unless method_defined? "#{status.name.downcase}?"
define_method("#{status.name.downcase}?") do
job_status_id == status.id
end
end
end
end
end
class JobStatus < ActiveRecord::Base
has_many :jobs
end
job_statuses
表包含一些種子數據,因此不會經常更改,但是如果我需要添加新狀態,則不必添加更多代碼即可獲取用於該新狀態的布爾方法。
但是,我不知道如何測試這些方法,因為當rspec的啟動job_statuses
表顯然是空的,當JobStatus
對象被創建, Job
被初始化,但由於還沒有對象存在,它不會產生任何的方法,我的測試失敗了,因為這些方法不存在。
請注意,我將rspec與spork&guard一起使用,並將數據庫清潔器與截斷策略一起使用(根據Railscast#257的要求 ,因為我使用的是Selenium),所以可能會使事情復雜化。
我想到的解決方案是將運行時方法的創建抽象到一個庫文件中,然后在我的測試文件中,在每次測試之前刪除並重新聲明我的類,並在最后添加實際的類(和藍圖)。套房:
describe AssociationPredicate do
before(:all) do
["Continuous", "Standard"].each { |type| JobType.create!(:job_type => type) }
["Requisition", "Open", "Paused", "Closed"].each { |status| JobStatus.create!(:job_status => status) }
end
after(:all) do
DatabaseCleaner.clean_with :truncation, :only => %w( job_types job_statuses )
# Reload Job model to remove changes
Object.send(:remove_const, 'Job')
load 'job.rb'
load 'support/blueprints.rb'
end
before(:each) do
Object.send(:remove_const, 'Job')
# Redefine Job model for testing purposes
class Job < ActiveRecord::Base
belongs_to :job_type
belongs_to :job_status
has_many :job_applications
end
end
it "should add methods when included" do
Job.send(:association_predicate, :job_type)
job.should respond_to(:continuous?)
job.should respond_to(:standard?)
end
end
這樣,我為每個測試創建一個基本類,根據需要添加運行時方法,並在完成后返回實際的類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.