Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a controller constant in an rspec test under Rails 3

Using Rails 3.2 I have a controller in a subdirectory (e.g. /controllers/data_feeds/acme_feed_controller.rb)

This controller has some constants as below

class DataFeeds::AcmeFeedController < ApplicationController

  MY_CONSTANT = "hi

  def do_something do
    ...
  end

end

In my rspec controller spec (which is in /spec/controllers/data_feeds/acme_feed_controller_spec.rb) I want to access that constant and below are two ways I've tried it (both commented out in the code below)

describe AcmeFeedController do
  if "tests something" do
    #c = AcmeFeedController.MY_CONSTANT
    #c = DataFeeds::AcmeFeedController.MY_CONSTANT
  end
end

I'm clearly not understanding something about the scope in which the spec test is run. What do I need to do and equally important why (i.e. what's happening with the scopes).

Thanks for your help.

like image 485
hershey Avatar asked Dec 05 '22 15:12

hershey


2 Answers

Constants cannot be referenced with dot syntax, so DataFeeds::AcmeFeedController.MY_CONSTANT would never work in any context. You need to use :: to reference constants: DataFeeds::AcmeFeedController::MY_CONSTANT.

Note that is a ruby issue and has nothing to do with RSpec. When you face an issue like this, I recommend you figure out how to do it with plain ruby (e.g. in IRB) before worrying about how it works in RSpec (usually it will be the same, anyway).

If you want to know how constants work in ruby, I commend you watch this talk that explains them in detail.

like image 62
Myron Marston Avatar answered Dec 25 '22 23:12

Myron Marston


Also, you can do this without repeating controller class name spaces.

describe AcmeFeedController do
  if "tests something" do
    c = controller.class.const_get('MY_CONSTANT')
  end
end

This kind of trick may not be approved in application codes, but in tests it may be.

like image 37
hiroshi Avatar answered Dec 26 '22 00:12

hiroshi