Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test instance variable was instantiated in controller with RSpec

Tags:

ruby

rspec

I'm trying to check that a new action in my RESTful controller set up an instance variable of the required Object type. Seems pretty typical, but having trouble executing it

Client Controller

def new   @client = Client.new end   

Test

describe "GET 'new'" do   it "should be successful" do     get 'new'     response.should be_success   end    it "should create a new client" do     get 'new'     assigns(:client).should == Client.new   end end 

Results in...

 'ClientsController GET 'new' should create a new client' FAILED   expected: #,        got: # (using ==) 

Which is probably because it's trying to compare 2 instances of active record, which differ. So, how do I check that the controller set up an instance variable that holds a new instance of the Client model.

like image 359
fakingfantastic Avatar asked Jan 12 '10 18:01

fakingfantastic


2 Answers

technicalpickles in #rspec helped me out...

assigns(:client).should be_kind_of(Client) 
like image 124
fakingfantastic Avatar answered Nov 13 '22 02:11

fakingfantastic


You can use Rails' new_record? method to check if a given instance has been saved to the database already or not:

assigns(:client).should be_a(Client) assigns(:client).should be_new_record 

(You can't use assigns[:client] for historical reasons, according to: http://guides.rubyonrails.org/testing.html#the-four-hashes-of-the-apocalypse)

like image 26
Attila Györffy Avatar answered Nov 13 '22 00:11

Attila Györffy