【问题标题】:Rspec and Capybara object matchingRspec 和 Capybara 对象匹配
【发布时间】:2011-07-23 20:16:47
【问题描述】:

使用 Rails 3.0.5、RSpec 2 和 Capybara 0.4.1.2,我正在尝试为我的 SessionsController#new 操作编写控制器规范。

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)>'

有什么提示吗?

【问题讨论】:

    标签: ruby-on-rails-3 session rspec2 capybara


    【解决方案1】:

    问题是如果你这样做了

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

    你会得到错误,因为这两个对象都有一个单独的object_id

    试试这个:

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

    【讨论】:

    • 谢谢,这行得通。出于好奇...如果我在这里使用be_anbe_an_instance_of 会有什么不同吗?
    • 啊,是的。 be_an 检查 kind_of?be_an_instance_of 检查 instance_of?。因此,对于从 AR::Base::Session 继承的任何类的每个实例,be_an 也都为真。更多信息:stackoverflow.com/questions/3893278/…
    • 您也可以使用#inspect 方法来比较两个对象的内容。 assigns(:session).inspect.should == ActiveRecord::Base::Session.new.inspect.
    猜你喜欢
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多