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.

4

2 回答 2

1

解决了!测试现在如下所示:

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

我的错:

  1. 不使用冒号在assigns.
  2. assigns.
于 2012-12-26T16:58:13.797 回答
0

尝试将toyController 中的变量替换为@toy. assigns只能访问实例变量。

于 2012-12-26T16:44:05.483 回答