第 5 章 控制器测试
5.1基础
rails generate rspec:controller home
RSpec.describe HomeController,
type: :controller
do
describe '#index' do
it "responds successfully" do
get :index
expect(response).to be_success
# response 对象包含应用返回给浏览器的所有数据,包括 HTTP 响应码。
# be_success 检查响应的状态是成 功(200 响应)还是失败(例如 500 异常)。
expect(response).to have_http_status "200"
end
end
end
be_success匹配器 ,have_http_status()匹配器
5.2要验证身份的controller test
如果程序有Devise。测试的时候,需要身份验证,则使用Devise Test helpers
Devise includes some test helpers for controller and integration tests. In order to use them, you need to include the repective module in you test cases/specs.
包含一个测试模块.
class PostsControllerTest < ActionController::TestCase include Devise::Test::ControllerHelpers end
class PostsTests < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers end
RSpec.configure do |config| config.include Devise::Test::IntegrationHelpers, type: :feature
config.include Devise::Test::ControllerHelpers, type: :controller
config.include Devise::Test::ControllerHelpers, type: :view
end
然后就可以使用sign_in, sign_out方法了
redirect_to 匹配器
以下测试都是get的测试。
ProjectsController
#inde
as an authenticated user
responds successfully
returns a 200 response
as a guest
returns a 302 response
redirects to the sign_in page
#show
as an authorized user
responds successfully
as an unauthorized user
redirects to the dashboard
5.3 测试用户输入。
HTTP GET外,还有POST, PATCH, DELETE与controller交互。