Question

I'm using Ruby 1.9.3p392 and rails 3.2.17

I have devices. A device belongs to a device type, and a device status. In my Device model, i have setup dynamic scope as follow:

DeviceStatus.all.each do |device_status|
    scope device_status.name, where(:device_status_id => device_status.id)
end

the name property of device status only allows [0-9a-zA-Z] It basically creates a scope for each device status I have in the DB.

I have 3 device statuses, Active, Unused and Obsolete

In the console, I can use:

DeviceType.all.each do |d|
    DeviceStatus.all.each do |s|
        p d.devices.send(s.name).count
    end
end

And I get the expected result: the count of different statuses, per device type.

I have this in a view and it works flawlessly. I also use this method to filter my index.html.erb from the controller using dynamic scopes selected by the user. I also use the same principle with other classes for filtering the index.html.erb

However, my problem appears when I run my functional tests, where I get the following error message in my view:

undefined method for 'Active' []:ActiveRecord::Relation

If I try to avoid associations and just replace d.devices.send() in my loop with Devices.send() i get:

undefined method for 'Active' #<Class:0xxxxxxxx>

Has anyone seen that before ?

Was it helpful?

Solution 2

I think I found the issue.

When executing rake test:functionals, the database is cleared and fixtures are loaded in the database after the models are processed.

So when the Device model is loaded, there is no DeviceStatus in the database, resulting in the model not creating the scopes. The fixtures are loaded after that and the test fails when trying to call a scope that doesn't exist on my Device relation.

OTHER TIPS

It looks like d.devices will be an array of ActiveRecord objects as DeviceType will have many Devices. I think you needs to do one of the following as par your requirement:

p d.devices[0].send(s.name).count

or

DeviceType.all.each do |d|
    DeviceStatus.all.each do |s|
        d.devices..each do |device|
           p device.send(s.name).count
        end   
    end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top