我正在设计控制器测试,但总是失败因为总是返回nil,请帮助找到问题所在,感谢百万!
posts_controller_spec.rb:
RSpec.describe PostsController, :type => :controller do
describe "with valid session" do
describe "GET index" do
it "assigns all posts as @posts" do
sign_in :admin, @user
post = create(:post)
get :index, {}
expect(assigns(:posts)).to eq([post])
end
end
end
...
end
posts_controller.rb
class PostsController < ApplicationController
before_action :authenticate_user!
before_action :set_post, only: [:show, :edit, :update, :destroy]
# GET /posts
# GET /posts.json
def index
@posts = Post.all
end
...
end
我在spec / rails_helper.rb
中加入了设计测试助手config.include Devise::TestHelpers, type: :controller
在我的情况下,post是在admin下的作用域,不确定这是否有所不同(功能测试没有通过路由?),所以我只在这里包含我的routes.rb
routes.rb中:
Rails.application.routes.draw do
root to: 'home#index'
get 'admin', to: 'admin#index'
devise_for :users
scope '/admin' do
resources :posts
end
end
最后,来自rspec的输出:
1) PostsController with valid session GET index assigns all posts as @posts
Failure/Error: expect(assigns(:posts)).to eq([post])
expected: [#<Post id: 57, title: "MyText", body: "MyText", image_url: "MyString", created_at: "2014-09-02 14:36:01", updated_at: "2014-09-02 14:36:01", user_id: 1>]
got: nil
(compared using ==)
# ./spec/controllers/posts_controller_spec.rb:53:in `block (4 levels) in <top (required)>'
我已阅读此帖子rspec test of my controller returns nil (+factory girl),并按照建议将get :index
更改为controller.index
。建议如果通过测试,那么这是一个路由问题。它确实通过了测试,但我仍然不知道路由问题在哪里,以及为什么get :index
无效......
答案 0 :(得分:1)
这只是一个小错误:在使用devise sign_in
之前创建一个用户RSpec.describe PostsController, :type => :controller do
describe "with valid session" do
let (:user) { create(:user) }
describe "GET index" do
it "assigns all posts as @posts" do
sign_in user
post = create(:post)
get :index, {}
expect(assigns(:posts)).to eq([post])
end
...
end
end
end