Search code examples
ruby-on-railsfunctional-testing

How can I test the availability of instance variables in my controller?


I'm using decent_exposure to present some instance_variables :

expose(:my_custom_variable) { current_user.my_variable }

So now this variable is accessible within my controller as my_custom_variable .

But I would like to ensure it's there with my test.

assert_not_nil my_custom_variable

Which does not work. If I put a debugger in my test, there's no way for me to access this variable. I've tried all of the following..

@controller.instance_variable_get("@my_custom_variable")
@controller.instance_variable_get("my_custom_variable")
@controller.instance_variable_get(:my_custom_variable)
@controller.assigns(:@my_custom_variable)
assigns(:my_custom_variable)
@controller.get_instance(:my_custom_variable)
@controller.get_instance("my_custom_variable")
@controller.get_instance("@my_custom_variable")

None of this works.. Any ideas?

Note: I am not using rspec. This is built in rails functional tests.


Solution

  • There are some examples on the decent_exposure page at the bottom.

    Testing

    Controller testing remains trivially easy. The shift is that you now set expectations on methods rather than instance variables. With RSpec, this mostly means avoiding assign and assigns.

    describe CompaniesController do
      describe "GET index" do
    
        # this...
        it "assigns @companies" do
          company = Company.create
          get :index
          assigns(:companies).should eq([company])
        end
    
        # becomes this
        it "exposes companies" do
          company = Company.create
          get :index
          controller.companies.should eq([company])
        end
      end
    end
    

    View specs follow a similar pattern:

    describe "people/index.html.erb" do
    
      # this...
      it "lists people" do
        assign(:people, [ mock_model(Person, name: 'John Doe') ])
        render
        rendered.should have_content('John Doe')
      end
    
      # becomes this
      it "lists people" do
        view.stub(people: [ mock_model(Person, name: 'John Doe') ])
        render
        rendered.should have_content('John Doe')
      end
    
    end