ruby-on-rails-3 – RSpec中的动态define_method抛出错误
发布时间:2020-12-17 01:59:12 所属栏目:百科 来源:网络整理
导读:我很确定我在这里错过了一个基本错误,所以我希望另一组眼睛可能会有所帮助.我使用的是Rails 3,Ruby 1.9.2和Rspec 2. 我想在模型上定义动态类方法,以便在将可分配对象(例如帐户)添加到系统时返回基本角色.例如: BaseRole.creator_for_account 通过控制台一切
我很确定我在这里错过了一个基本错误,所以我希望另一组眼睛可能会有所帮助.我使用的是Rails 3,Ruby 1.9.2和Rspec 2.
我想在模型上定义动态类方法,以便在将可分配对象(例如帐户)添加到系统时返回基本角色.例如: BaseRole.creator_for_account 通过控制台一切正常: ruby-1.9.2-p180 :003 > BaseRole.respond_to?(:creator_for_account) => true 但是当我为任何类方法运行我的规范时,无论在哪里调用规范中的方法,我都会得到NoM??ethodError.我假设关于我如何动态声明方法的东西不是用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中包含Module # /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 解决方法
您的项目中是否有另一个类或具有相同名称的规范,但是没有添加动态方法?我和你有完全相同的问题,并重命名其中一个类修复它.
我的猜测是其他课程首先加载 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |