Question

I have an instance method on my Writer class that uses the defined? operator to check and see if posted_posts is defined:

def performance_score
  logger.debug posted_posts
  logger.debug defined?(posted_posts)
  unless defined?(posted_posts)
    ...
  else
    ...
  end
end

In my controller I have a writers instance defined as follows:

@writers = Writer.select("writers.*, p.total_posts, p.posted_posts").joins(...)

When I call @writers.performance_score, from the first logger.debug line it says I have 4 posted_posts, but the second prints out nil. Furthermore, it goes into the unless section instead of the else.

To test this, I stub out the posted_posts to 4. This prints out 4 from the first logger.debug line and the second logger.debug says it is defined as a method. Furthermore, it does go into the else.

Can you please help me understand why this is failing in my Rails application?

Was it helpful?

Solution

It is likely failing in reality because the relation returned from your AREL select statement uses method_missing magic to return a value from the call. This is not the same thing as being defined. When you mock/stub the "method" on your test object it is likely using the define_method function which is creating a defined function.

This may do what you want instead.

if respond_to?(:posted_posts)
  ...
else
  ...
end

OTHER TIPS

don't use the same variable name after u query the AR abject,

@results = @writers.select("writers.*, p.total_posts, p.posted_posts")

then call @results.performance_score in your controller

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top