Rails测试分三种:
1,关注于一个单独的Model的单元测试Unit test
2,关注于一个单独的Controller和它使用的models之间的交互的功能测试Functional test
3,关注story级的多个controllers的多个actions之间的交互的集成测试Integration test
今天我们就来看看跨越多个controllers的集成测试
IntegrationTesting/test/integration/stories_test.rb
require "#{File.dirname(__FILE__)}/../test_helper"
class StoriesTest < ActionController::IntegrationTest
fixtures :accounts, :ledgers, :registers, :people
def test_signup_new_person
go_to_login
go_to_signup
signup :name => "Bob",
:user_name => "bob",
:password => "secret"
end
private
def go_to_login
get "/login"
assert_response :success
assert_template "login/index"
end
def go_to_signup
get "/signup"
assert_response :success
assert_template "signup/index"
end
def signup(options)
post "/signup", options
assert_response :redirect
follow_redirect!
assert_response :success
assert_template "ledger/index"
end
end
其中我们将一些通用的流程做成helper方法,如go_to_login,go_to_signup,signup
我们甚至可以将登录认证等通用流程做成一个helper方法并放在我们自己的DSL模块里:
require "#{File.dirname(__FILE__)}/../test_helper"
class StoriesTest < ActionController::IntegrationTest
fixtures :accounts, :ledgers, :registers, :people
def test_multiple_users
jim = new_session_as(:jim)
bob = new_session_as(:bob)
stacey = new_session_as(:stacey)
jim.selects_ledger(:jims)
jim.adds_account(:name => "checking:)
bob.goes_to_preferences
stacey.cancels_account
end
private
module MyTestingDSL
attr_reader :person
def logs_in_as(person)
@person = people(person)
post authenticate_url, :user_name => @person.user_name, :password => @person.password
is_redirected_to "ledger/list"
end
def goes_to_preferences
# ...
end
def cancels_account
# ...
end
def new_session_as(person)
new_session do |sess|
sess.goes_to_login
sess.logs_in_as(person)
yield sess if block_given?
end
end
end
我们会发现集成测试比单独Controller的功能测试慢许多,因为集成测试涉及的东西太多