4

我正在尝试将 RSpec 与 Mongoid 和 rails-api 一起使用。我使用的宝石是rspec-railsmongoid-rspec。一切都很好,除了这个小东西:

# users_controller_spec.rb
describe "GET index" do
  it "assigns all users as @users" do
    user = User.create! valid_attributes
    get :index, {}, valid_session
    assigns(:users).should eq([user])
  end
end

# users_controller.rb
def index
  @users = User.all
  render json: @users
end

这样做时,我只收到此错误消息:

Failures:

  1) UsersController GET index assigns all users as @users
     Failure/Error: assigns(:users).should eq([user])

       expected: [#<User _id: 50c8b84606027eb8aa000001, _type: nil, created_at: 2012-12-12 17:00:54 UTC, updated_at: 2012-12-12 17:00:54 UTC, name: "testuser", email: "testuser@gmail.com">]
            got: #<Mongoid::Criteria
         selector: {}
         options:  {}
         class:    User
         embedded: false>


       (compared using ==)

       Diff:
       @@ -1,2 +1,6 @@
       -[#<User _id: 50c8b84606027eb8aa000001, _type: nil, created_at: 2012-12-12 17:00:54 UTC, updated_at: 2012-12-12 17:00:54 UTC, name: "testuser", email: "testuser@gmail.com">]
       +#<Mongoid::Criteria
       +  selector: {}
       +  options:  {}
       +  class:    User
       +  embedded: false>

     # ./spec/controllers/users_controller_spec.rb:41:in `block (3 levels) in <top (required)>'
4

1 回答 1

1

@users = User.all是延迟加载的,所以实际的对象是一个 Criteria。

您可以检查标准,也可以像这样使用数组:

assigns(:users).to_a.should eq([user])
于 2013-02-12T03:33:56.277 回答