ruby-on-rails - 如何使用 rspec 在我的 Controller 的新操作中测试实例变量的分配?

标签 ruby-on-rails ruby ruby-on-rails-3 testing rspec

我对测试还很陌生,并且有一个我想测试的 UsersController。我从新的 Action 开始,到目前为止有以下内容;

require 'spec_helper'

describe UsersController do

  describe "GET 'new'" do
    it "assigns a new User to @user" do
      user = User.new
      get :new
      assigns(:user).should eq(user)
    end
    it "renders the :new template"
  end

end

到目前为止,我的 UsersController 看起来像这样

class UsersController < ApplicationController
  def new
    @user = User.new
  end
end

我预计我的第一个测试会成功,但当我运行它时,我得到以下信息;

Failures:

  1) UsersController GET 'new' assigns a new User to @user
     Failure/Error: assigns(:user).should eq(user)

       expected: #<User id: nil, email: nil, username: nil, password_digest: nil, created_at: nil, updated_at: nil>
            got: #<User id: nil, email: nil, username: nil, password_digest: nil, created_at: nil, updated_at: nil>

       (compared using ==)

       Diff:#<User:0x007fe4bbfceed0>.==(#<User:0x007fe4bce5c290>) returned false even though the diff between #<User:0x007fe4bbfceed0> and #<User:0x007fe4bce5c290> is empty. Check the implementation of #<User:0x007fe4bbfceed0>.==.
     # ./spec/controllers/users_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

在控制台中运行显示以下内容;

irb(main):001:0> a = User.new
=> #<User id: nil, email: nil, username: nil, password_digest: nil, created_at: nil, updated_at: nil>
irb(main):002:0> b = User.new
=> #<User id: nil, email: nil, username: nil, password_digest: nil, created_at: nil, updated_at: nil>
irb(main):003:0> a == b
=> false

所以现在我很好奇为什么 2 个空的 ActiveRecord 对象不相等(毕竟 Array.new == Array.new 返回 true),以及我必须做什么才能使我的考试通过了。

最佳答案

您可能应该将测试更改为如下内容:

describe UsersController do

  describe "GET 'new'" do
    it "assigns a new User to @user" do
      get :new
      assigns(:user).should be_new_record
      assigns(:user).kind_of?(User).should be_true
    end
    it "renders the :new template"   end

end

你也会有同样的效果。如果两个对象未保存,则它们没有主键,Rails 将使用 object_id 相等性来比较它们,这就是它们不是 == 的原因。

关于ruby-on-rails - 如何使用 rspec 在我的 Controller 的新操作中测试实例变量的分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10870694/

相关文章:

mysql - rails mysql 编码问题/问题 - Mysql::Error: 非法混合排序规则 (latin1_swedish_ci,IMPLICIT) 和 (utf8_general_ci,COERCIBLE)

html - 为什么高度为: auto not provide content area large enough to fit my content?

mysql - 执行用户迁移时出错

ruby - 使用 Ruby 和 Sinatra,尝试填充页面上的某个区域而不重新加载整个页面

ruby - sinatra :public is not returning a path as expected. 中的错误或功能?

ruby-on-rails-3 - 在 Ruby on Rails 3/Postgres/Apache Passenger 应用程序中跟踪内存泄漏

ruby-on-rails - rails : cattr_accessor and class variables

ruby - 在 Mechanize 请求之间维护 cookie

ruby-on-rails-3 - 如何使用 Rspec 测试载波版本大小

ruby - 按组大小排列的 Active Record 顺序