我跟着一個關於使用Rspec進行測試的教程。嘗試運行測試時出現語法錯誤。這裏是我的測試代碼:在Rspec上加載文件錯誤
require 'rails_helper'
RSpec.describe CommentsController, type: :controller do
describe "comments#create action" do
it "should allow admins to create comments on posts" do
post = FactoryGirl.create(:post)
admin = FactoryGirl.create(:admin)
sign_in admin
post :create, params: { post_id: post.id, comment: { message: 'awesome post' } }
expect(response).to redirect_to root_path
expect(post.comments.length).to eq 1
expect(post.comments.first.message).to eq "awesome gram"
end
it "should require an admin to be logged in to comment on a post" do
post = FactoryGirl.create(:post)
post :create, params: { post_id: post.id, comment: { message: 'awesome post' } }
expect(response).to redirect_to new_admin_session_path
end
it "should return http status code of not found if the post isn't found" do
admin = FactoryGirl.create(:admin)
sign_in admin
post :create, params: { post_id: 'SUNSHINE', comment: { message: 'awesome post'} }
expect(response).to have_http_status :not_found
end
end
end
這裏的控制器:
class CommentsController < ApplicationController
before_action :authenticate_admin!, only: [:create]
def create
@post = Post.find_by_id(params[:post_id])
return render_not_found if @post.blank?
@post.comments.create(comment_params.merge(admin: current_admin))
redirect_to root_path
end
private
def render_not_found(status=:not_found)
render plain: "#{status.to_s.titleize} :(", status: status
end
def comment_params
params.require(:comment).permit(:message)
end
end
這裏的運行測試時,端子輸出:
有什麼奇怪的是,當我發表意見線那些正在產生錯誤的測試,測試在最後一次測試通過時按預期運行。我已經檢查了測試文件以及描述相同問題的類似帖子,它在語法上是正確的。 Rails新手如此赦免菜鳥的錯誤。
啊這是有道理的。我有一個後期模型,所以我有條件輸入所有的測試。謝謝! –