2
我有設計的控制器測試,但它總是失敗,因爲指定總是返回零,請幫助找到問題的位置,謝謝!Rspec測試設計失敗,因爲指定始終爲零
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
我已經包括在規範制定測試傭工/ rails_helper.rb
config.include Devise::TestHelpers, type: :controller
在我的情況下,後在管理員範圍內,不確定是否有區別(功能測試不通過路由?),所以我只包括我的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
是不工作...