我目前停留在Michael Hartl(railstutorial.org)第13章
的导轨教程中并收到以下两个错误:
1) Error:
MicropostsControllerTest#test_should_redirect_create_when_not_logged_in:
ActionController::UrlGenerationError: No route matches {:action=>"/microposts", :controller=>"microposts", :params=>{:micropost=>{:content=>"Lorem ipsum"}}}
test/controllers/microposts_controller_test.rb:11:in 'block (2 levels) in <class:MicropostsControllerTest>'
test/controllers/microposts_controller_test.rb:10:in 'block in <class:MicropostsControllerTest>'
2) Error:
MicropostsControllerTest#test_should_redirect_destroy_when_not_logged_in:
ActionController::UrlGenerationError: No route matches {:action=>"/microposts/499495288", :controller=>"microposts"}
test/controllers/microposts_controller_test.rb:18:in 'block (2 levels) in <class:MicropostsControllerTest>'
test/controllers/microposts_controller_test.rb:17:in 'block in <class:MicropostsControllerTest>'
据我所知,&#39;行动&#39;应该像get,post,delete等。 但是我不知道,为什么它会说&#39; micropost&#39;这里。
microposts_controller_test.rb的内容:
require 'test_helper'
class MicropostsControllerTest < ActionController::TestCase
def setup
@micropost = microposts(:orange)
end
test 'should redirect create when not logged in' do
assert_no_difference 'Micropost.count' do
post microposts_path, params: {micropost: {content: 'Lorem ipsum'}}
end
assert_redirected_to login_url
end
test 'should redirect destroy when not logged in' do
assert_no_difference 'Micropost.count' do
delete micropost_path(@micropost)
end
assert_redirected_to login_url
end
end
micropost_controller.rb的内容:
class MicropostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
flash[:success] = 'Micropost created!'
redirect_to root_url
else
render 'static_pages/home'
end
end
def destroy
end
private
def micropost_params
params.require(:micropost).permit(:content)
end
end
routes.rb的内容:
Rails.application.routes.draw do
root 'static_pages#home'
get '/help' => 'static_pages#help'
get '/about' => 'static_pages#about'
get '/contact' => 'static_pages#contact'
get '/signup' => 'users#new'
get '/login' => 'sessions#new'
post '/login' => 'sessions#create'
delete '/logout' => 'sessions#destroy'
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :microposts, only: [:create, :destroy]
end
感谢任何帮助。
由于
编辑:
在micropost_controller_test.rb中,它应该是:
class MicropostsControllerTest < ActionDispatch::IntegrationTest
而不是
class MicropostControllerTest < ActionCntroller::TestCase
答案 0 :(得分:0)
第一个测试的问题是你在控制器/微博中没有路线&#34;测试试图点击,如果你看到你的路线文件,它确认resources :microposts, only: [:create, :destroy]
,所以没有路由。其次,在销毁之后它应该重定向,并且在你的控制器方法中没有重定向。所以最终测试失败了。
答案 1 :(得分:0)
在micropost_controller_test.rb中,它应该是:
class MicropostsControllerTest < ActionDispatch::IntegrationTest
而不是
class MicropostControllerTest < ActionCntroller::TestCase