Pregunta

I'm trying to use RSpec together with Mongoid and rails-api. The Gems I'm using are rspec-rails and mongoid-rspec. Everything is fine except of this little thing:

# 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

When doing this I only get this error message:

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)>'
¿Fue útil?

Solución

@users = User.all is lazy loaded, so the actual object is a Criteria.

You can either check against the criteria, or use the array like this:

assigns(:users).to_a.should eq([user])
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top