Rails5 還在 beta 當(dāng)中,但是即將來(lái)臨的版本升級(jí)有相當(dāng)多的改變(列如新功能 ActionCable),其中之一是針對(duì) controller testing. 在 Rails5 升級(jí)之下,controller test 改為繼承 ActionDispatch::IntegrationTest, 而且ActionDispatch::IntegrationTest 并沒(méi)有 ActionController::TestCase 的 assigns() 方式。
在很多現(xiàn)成項(xiàng)目環(huán)境之下,要開(kāi)始測(cè)試 Rails5 升級(jí),并且同時(shí)保持現(xiàn)有的測(cè)試庫(kù)必須使用 rails-controller-testing gem.
Gemfile:
group :test do
gem “rails-controller-testing”
end
Rails5 關(guān)于controller testing 語(yǔ)法有改變,除了 get 請(qǐng)求意外必須指定 controller action, 及 request method.
Rails 4.2
test “should show world” do
get :show, id: @world
assert_response :success
end
test “should update world” do
patch :update, id: @world, world: {title: “hello”}
assert_redirected_to world_path(assigns(:world))
end
rails 5.0.0.beta1
除了 get 以外,其他 controller action 必須改換 process,同時(shí)注意params 的用法改變。
test “should show world” do
get :show, params: {id: @world}
assert_response :success
end
test “should update world” do
process :update, method: :patch, params: {id: @world, world: {title: “hello”}}
assert_redirected_to world_path(assigns(:world))
end
References:
Comment
本文章寫(xiě)作時(shí)的 rails 版本為 5.0.0.beta1.