Rails: How to test dynamically define methods that are based on other model
I have a model called DeviceState which contains states like
"active","offline","online".
I have another model called Device which belongs_to to DeviceState.
Now, to have methods such as @device.active? and @device.offline? on the
device model I've defined a dynamic method like so:
DeviceState.all.each do |method|
define_method((method.name + "?").to_sym) do
self.device_state.name == method.name
end
end
My problem is that when I try to create tests on the Device model, the
dynamic method are not created because the DeviceState model hasn't been
populated on the database while the test environment started up. So by the
time I create the DeviceState data with factory girl it would be too late.
One solution I tried is to seed the DeviceState in spec_helper, however
while this worked for the first test I didn't work for all the rest as the
database cleaner removed the data.
So what would be the best way to overcome those dynamically defined methods?
Thanks.
No comments:
Post a Comment