Jeffrey Yong Jeffrey Yong - 15 days ago 5
Ruby Question

Assigns method returns nil in RSpec

I am doing my testing with mocks and stubs but I keep getting nil in my output. I am not sure if it's the problem with the assigns method. Could I also know how I should debug this kind of problem? I am using rspec-rails 3.5.2 Thank you.

The failing test:

describe 'guest user' do
describe 'GET index' do
let(:achievement) { instance_double(Achievement) }

before do
allow(Achievement).to receive(:get_public_achievements) { [achievement] }
end

it 'assigns public achievements to template' do
get :index
expect(assigns(achievement)).to eq([achievement])
end
end
end


The index action in the controller

def index
@achievements = Achievement.get_public_achievements
end


The get_public_achievements in the achievement model

def self.get_public_achievements
// empty method it's fine
end


The error:

1) AchievementsController guest user GET index assigns public achievements to template
Failure/Error: expect(assigns(achievement)).to eq([achievement])

expected: [#<InstanceDouble(Achievement) (anonymous)>]
got: nil

(compared using ==)

Answer

assigns is keyed by symbols. Should be

expect(assigns(:achievements)).to eq([achievement])
Comments