Jack Kinsella
Jack Kinsella

Reputation: 4631

how do you stub a local variable in an rspec controller test

I've just implemented OmniAuth (using Ryan Bates' Screencast http://asciicasts.com/episodes/235-omniauth-part-1) and am writing Rspec tests for the functionality and have ran into trouble testing the authentifications#create action. I'm at quite a loss as to how to test this one -- in particular how to stub the local variable omniauth. No matter what I try I keep can't get any tests to work.

Taking a cut down version of the action, how would you test that a new is called on User for example


#cut down version of the authentifications controller code I am attempting to test

  def create
    omniauth = request.env["omniauth.auth"]
    authentification = Authentification.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])     
    ....
    user = User.new
    ....
  end  

#example test

    it "should create a new user" do          
        subject.stub_chain(:request,:env) {{"omniauth.auth" => {'provider' =>1, 'uid' => 2}}}
        User.should_receive(:new)
        post :create
      end

Upvotes: 1

Views: 6392

Answers (1)

Arkan
Arkan

Reputation: 6236

I Did that :

class SessionsController < ApplicationController 
  def create 
    @user = User.find_by_auth_hash(auth_hash) 
  end 

  def auth_hash 
    request.env['omniauth.auth'] 
  end 
end 

describe SessionsController do 
  it 'should allow login' do 
    controller.stub!(:auth_hash).and_return({'provider' => 'twitter', 'uid' => '1234'}) 
    get :create, :provider => 'twitter' 
    assigns(:user).should_not be_nil 
  end 
end 

Hope that helps.

Upvotes: 3

Related Questions