2011-03-27 99 views
2

使用Rails 3.0.5,RSpec 2和水豚0.4.1.2,我試圖爲我的SessionsController#new行爲編寫控制器規範。Rspec和水豚對象匹配

it "assigns the empty session to a variable" do 
    get :new 
    assigns(:session).should == ActiveRecord::Base::Session.new 
end 

我使用ActiveRecord :: Base命名空間,因爲它似乎與Capybara Session類衝突,當我沒有。

這裏是SessionsController:

class SessionsController < ApplicationController 
    def new 
    @session = Session.new 
    end 
end 

RSpec的似乎並不明白這些是相同的對象。這裏是我的測試返回:

Failure/Error: assigns(:session).should == ActiveRecord::Base::Session.new 
    expected: #<Session id: nil, session_id: nil, data: nil, created_at: nil, updated_at: nil> 
     got: #<Session id: nil, session_id: nil, data: nil, created_at: nil, updated_at: nil> (using ==) 
    Diff: 
# ./spec/controllers/sessions_controller_spec.rb:17:in `block (3 levels) in <top (required)>' 

任何提示?

回答

3

的問題是,如果你做

ActiveRecord::Base::Session.new == ActiveRecord::Base::Session.new 

你會得到錯誤的,因爲這兩個對象都有一個單獨的object_id

試試這個:

assigns(:session).should be_an(ActiveRecord::Base::Session) 
+0

謝謝,這個作品。出於好奇...如果我在這裏使用'be_an'或'be_an_instance_of',它會有所作爲嗎? – Cimm 2011-03-27 10:35:50

+0

啊是的。 'be_an'檢查'kind_of?','be_an_instance_of'檢查'instance_of?'。因此,對於從AR :: Base :: Session繼承的任何類的每個實例,be_an也是如此。更多信息:http://stackoverflow.com/questions/3893278/ruby-kind-of-vs-instance-of-vs-is-a – Dogbert 2011-03-27 10:41:52

+0

很酷,謝謝你的回答! – Cimm 2011-03-27 12:01:20