2011-05-16 26 views
4

我很確定我錯過了一個基本的錯誤,所以我希望另一組眼睛可能會有所幫助。我正在使用Rails 3,Ruby 1.9.2和Rspec 2.RSpec中的動態define_method拋出錯誤

我想在模型上定義動態類方法,以便在添加到可分配對象(如帳戶)時返回基本角色系統。例如:

BaseRole.creator_for_account 

一切通過控制檯正常工作:

ruby-1.9.2-p180 :003 > BaseRole.respond_to?(:creator_for_account) 
=> true 

但是當我跑我的規格對於任何類的方法,我得到一個NoMethodError無論我呼籲在規範的方法。我假設我是如何動態聲明方法的東西不是用RSpec拼湊出來的,但我似乎無法弄清楚爲什麼。

lib目錄是自動加載路徑,並且這些方法對respond_to?返回true。

# /lib/assignable_base_role.rb 
module AssignableBaseRole 
    def self.included(base) 
    base.extend(ClassMethods) 
    end 

    module ClassMethods 
    BaseRole.all.each do |base_role| 
     role_type = RoleType.find(base_role.role_type_id) 
     assignable_name = base_role.assignable_type.downcase 
     method = "#{role_type.name}_for_#{assignable_name}" 

     define_method(method) do 
     self.where(:role_type_id => role_type.id, 
       :assignable_type => assignable_name).first 
     end 
    end 
    end 
end 

然後包括在BaseRole

# /models/base_role.rb 
class BaseRole < ActiveRecord::Base 
    include AssignableBaseRole 

    belongs_to :role 
    belongs_to :role_type 

    ...... 
    ...... 

end 

然後在我的規格模塊:

it "adds correct authority for creator role" do 
    create_assignment 
    base_role = BaseRole.creator_for_account # <== NoMethodError here 
    user1 = Factory.create(:user) 
    account.users << user1 
    user1.roles_for_assignable(account).should include(base_role.role) 
    end 
+0

如果您刪除模塊,它仍然是一個問題?我也在類文件中使用define_method來獲得這個,只有在guard後面使用rspec。 – 2013-11-23 05:37:29

回答

0

看樣子你是基於數據庫值定義這些方法:

BaseRole.all.each do |base_role| 
..... 

難道是「crea tor「作爲角色類型不存在於測試數據庫中,或者」account「不存在作爲assignable_type?

大概你是在控制檯上測試這個進行開發,而不是測試,所以數據可能不匹配。可能需要在掛鉤之前設置數據。

+0

感謝您的回覆,我確實驗證了測試數據的存在。我正在通過數據庫加載數據,並且正在開發中使用控制檯,主要是爲了看看是否會定義方法,因爲RSpec中有些奇怪。但是你可能會用前面的書和/或以某種方式預加載數據。這可能是不同的東西如何加載和/或當我玩控制檯與測試環境。 – 2011-05-16 22:18:31

+0

很酷。有興趣聽聽你的發現。 – twmills 2011-05-17 18:25:00

1

您的項目中是否有另一個類或具有相同名稱的規格,但沒有添加動態方法?我和你有完全相同的問題,並且重命名其中一個類修復了它。

我的猜測是其他類正在首先加載