0

Having trouble testing variable values from a controller using RSpec.

Relevant controller code:

class ToysController < ApplicationController

  def claim
    toy = Toy.find(params[:toy_id])
    current_user.toys << toy
    toy.status = "claimed"
    render :index
  end

end

This definitely works -- I know because I puts toy.inspect after it happens, and it's fine. But I can't test it. Here's what my current test looks like, after a lot of messy attempts:

require 'spec_helper'

describe ToysController do

  describe "GET 'claim'" do
    let(:james) {create(:user)}
    let(:toy) {create(:toy)}

    before do
      OmniAuth.config.mock_auth[:google] = {
          uid: james.uid
      }
      session[:user_id] = james.id
    end

    it "can be claimed by a user" do
      get :claim, toy_id: toy.id
      assigns(:toy).user.should eq james.id
    end

  end

end

When I run the test, I get all sorts of errors on assigns(:toy).user.should indicating that toy is Nil. I've tried messing with the assigns syntax in lots of ways, because I was unable to find the docs for it.

What am I doing wrong? What's the right way to see what the controller does with the user and the toy passed to it?

Edit: Trying to phase over to instance variables, but it still doesn't do the trick. Here's my code again with instance variables (different var names, same results):

Ideas controller:

def claim
  @idea = Idea.find(params[:idea_id])
  current_user.ideas << @idea
  @idea.status = "claimed"
  render :index
end

Test:

describe "GET 'claim'" do
  let(:james) {create(:user)}
  let(:si_title) {create(:idea)}

  before do
    OmniAuth.config.mock_auth[:google] = {
        uid: james.uid
    }
    session[:user_id] = james.id
  end

  it "can be claimed by a user" do
    get :claim, idea_id: si_title.id
    puts assigns(si_title).inspect

  end
end

Output: nil.

ezuk
  • 3,096
  • 3
  • 30
  • 41

2 Answers2

1

Solved! Test now reads like this:

describe "GET #claim" do
  let(:james) {create(:user)}
  let(:si_title) {create(:idea)}

  before do
    OmniAuth.config.mock_auth[:google] = {
        uid: james.uid
    }
    session[:user_id] = james.id
  end

  it "can be claimed by a user" do
    get :claim, idea_id: si_title.id
    assigns(:idea).user_id.should eq james.id
  end

end

My mistakes:

  1. Not using a colon to prefix the instance variable name in the assigns.
  2. Using the incorrect variable name in the assigns.
ezuk
  • 3,096
  • 3
  • 30
  • 41
0

Try replacing toy variable in Controller with @toy. assigns has access only to instance variables.

atmaish
  • 2,495
  • 3
  • 22
  • 25
  • Tried that, but it's not working... Please see refactored code above (edited my question) – ezuk Dec 26 '12 at 16:49