Dynamic define_method metadata error in RSpec

I am sure that the main mistake is missing here, so I hope a different set of eyes can help. I use Rails 3, Ruby 1.9.2 and Rspec 2.

I would like to define dynamic class methods for the model so that I can return the base roles for the assigned object (for example, the account) as they are added to the system. For instance:

BaseRole.creator_for_account 

Everything works fine through the console:

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

but when I run my specifications for any of the class methods, I get a NoMethodError wherever I call the method in the specification. I assume that something about how I dynamically declare methods is not jiving with RSpec, but I cannot understand why.

lib dir is the autoload path, and the methods return true for response_to ?.

 # /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 

Then enable the module in BaseRole

 # /models/base_role.rb class BaseRole < ActiveRecord::Base include AssignableBaseRole belongs_to :role belongs_to :role_type ...... ...... end 

Then in my specification:

  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 
+4
source share
2 answers

Do you have another class in your project or specification with the same name, but have dynamic methods been added? I had the same problem as you, and renamed one of the classes, fixed it.

I assume another class is loading first.

+1
source

It seems you are defining these methods based on the values โ€‹โ€‹in the database:

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

Could it be that the "creator" does not exist in the test database as a role type, or the "account" does not exist as assignable_type?

Presumably, you are testing this in the console for development and not for testing, so the data may be incompatible. You may need to tweak the data in before hook.

0
source

All Articles