使用CommentsController
测试RSpec
时出现以下错误:
ActionController::UrlGenerationError:
No route matches {:action=>"create", :comment=>{:comment=>"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, :controller=>"comments"}
spec / models / comment_spec.rb
RSpec.describe CommentsController, type: :controller do
let!(:user) { create(:user) }
let!(:post1) { create(:post, user: user) }
let!(:comment) { create(:comment, user_id: user.id, post_id: post1.id) }
let!(:comment_attributes) { attributes_for(:comment) }
describe "#create" do
before do
sign_in user
end
it 'save post' do
expect do
post :create, params: { comment: comment_attributes }, session: {}
end.to change(Comment, :count).by(1)
end
it 'if post saves, redirect_to posts page' do
post :create, params: { post: comment_attributes }, session: {}
expect(response).to redirect_to(posts_path)
end
end
end
答案 0 :(得分:2)
每次创建新资源(要通过链接访问)时,都必须更新routes.rb
文件,否则Rails不知道在给定URL中使用哪个控制器。在resources :comments
中添加routes.rb
行可以为您完成此操作。