2011-03-27 161 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