我的控制器的 rspec 测试返回零(+工厂女孩) [英] rspec test of my controller returns nil (+factory girl)

查看:17
本文介绍了我的控制器的 rspec 测试返回零(+工厂女孩)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Rails 上使用 rspec 和 factory girl 学习测试,但我无法让它们工作.

I am learning tests with rspec and factory girl on Rails and I can't manage to make them work.

我的用户控制器如下所示:

My User controller looks like this :

class UsersController < ApplicationController
  def index
    @users = User.all.order(:first_name)
  end
end

和测试:

require 'spec_helper'

describe UsersController do

before(:each) do
    @user1 = FactoryGirl.create(:user, first_name: "B", last_name: "B", uid: "b")
    @user2 = FactoryGirl.create(:user, first_name: "A", last_name: "A", uid: "a")
end

describe "GET index" do     
    it "sets a list of users sorted by first name" do
        get :index
        assigns(:users).should == [@user2, @user1]
    end
end
end

但测试返回以下内容:

UsersController GET index sets a list of users sorted by first name
Failure/Error: assigns(:users).should == [@user2, @user1]
expected: [#<User id: nil, email: nil, first_name: "A", last_name: "A", uid: "a", active: true, admin: false, created_at: nil, updated_at: nil, reset_date: nil>, #<User id: nil, email: nil, first_name: "B", last_name: "B", uid: "b", active: true, admin: false, created_at: nil, updated_at: nil, reset_date: nil>]
got: nil (using ==)
# ./spec/controllers/users_controller_spec.rb:13:in `block (3 levels) in <top (required)>'

你知道我做错了什么吗?

Do you have any idea what I am doing wrong ?

干杯!

这是'耙路线':

      Prefix Verb   URI Pattern                        Controller#Action
        root GET    /                                  meetings#index
    meetings GET    /meetings(.:format)                meetings#index
       login GET    /login(.:format)                   sessions#new
      logout GET    /logout(.:format)                  sessions#destroy
             POST   /auth/:provider/callback(.:format) sessions#create
auth_failure GET    /auth/failure(.:format)            sessions#failure
       users GET    /users(.:format)                   users#index
             POST   /users(.:format)                   users#create
    new_user GET    /users/new(.:format)               users#new
   edit_user GET    /users/:id/edit(.:format)          users#edit
        user GET    /users/:id(.:format)               users#show
             PATCH  /users/:id(.:format)               users#update
             PUT    /users/:id(.:format)               users#update
             DELETE /users/:id(.:format)               users#destroy

推荐答案

正如 Jvnill 上面所说,使用 create.另一种选择是在声明之后使用@user1.save.

As Jvnill said above, use create. The other option is to use @user1.save after declaring them.

此外,就路由而言,请检查路由文件中的资源.

Also as far as routes go, check your resources in the routes file.

这篇关于我的控制器的 rspec 测试返回零(+工厂女孩)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆