Search code examples
ruby-on-railsrubyrspecrspec-rails

Rails: accessing controller instance variables in rpec test


In an Rspec controller test I want to check the values of instance variables in my the controller that I am testing.

For example,

controller:

class ThingsController < ApplicationController
  def index
    @things = Thing.all
  end
end

spec:

RSpec.describe UsersController, type: :controller do
  describe 'GET #index' do 
    expect(@things).to_not be_nil
  end
end

How do I access @things in the above example?


Solution

  • This should do the trick:

    expect(assigns(:things)).to_not be_nil
    

    More likely you'll want something like:

    let(:thing) { ... }
    ...
    expect(assigns(:things)).to eq([thing])