Jeffrey Yong Jeffrey Yong - 1 year ago 75
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] }

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

The index action in the controller

def index
@achievements = Achievement.get_public_achievements

The get_public_achievements in the achievement model

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

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 Source

assigns is keyed by symbols. Should be

expect(assigns(:achievements)).to eq([achievement])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download