使用者必須登入才能建立 course#create
修改 app/contrllers/courses_controller
class CoursesController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
運行測試
$ rspec spec/controllers/courses_controller_spec.rb
........FFF..........
Failures:
1) CoursesController POST create when course doesn't have title render new template
Failure/Error: expect(response).to render_template("new")
expecting <"new"> but rendering with <[]>
2) CoursesController POST create when course has title create a new course record
Failure/Error:
expect do
post :create, params: { course: attributes_for(:course) }
end.to change { Course.count }.by(1)
expected result to have changed by 1, but was changed by 0
3) CoursesController POST create when course has title redirects to courses_path
Failure/Error: expect(response).to redirect_to courses_path
Expected response to be a redirect to <http://test.host/courses> but was a redirect to <http://test.host/users/sign_in>.
Expected "http://test.host/courses" to be === "http://test.host/users/sign_in".
Finished in 0.20329 seconds (files took 1.94 seconds to load)
21 examples, 3 failures
之前通過的場景都不成功了,因為現在需要先登入才可以操作。
修改 spec/controllers/courses_controller_spec.rb
中的 POST create
:
describe "POST create" do
let(:user) { create(:user) } # <--
before { sign_in user } # <--
context "when course doesn't have title" do
it "doesn't create a record" do
expect do
post :create, params: { course: { :description => "bar" }}
end.to change { Course.count }.by(0)
end
it "render new template" do
post :create, params: { course: { :description => "bar" } }
expect(response).to render_template("new")
end
end
context "when course has title" do
it "create a new course record" do
course = build(:course)
expect do
post :create, params: { course: attributes_for(:course) }
end.to change { Course.count }.by(1)
end
it "redirects to courses_path" do
course = build(:course)
post :create, params:{ course: attributes_for(:course) }
expect(response).to redirect_to courses_path
end
end
end
在所有的測試之前先登入即可。