Rails 4.2 集成测试 - 有没有办法重用测试代码?



如果我从检查用户可以登录的测试开始:

test "can login successfully" do
get "/session/new"
assert_select "h1", "Log in to the Portal"
assert_response :success
post "/session", { username: "nick1", password: "password1" }
assert_response :redirect
follow_redirect!
assert_select "h1", "Welcome to the Portal"
end

在我的其余测试中,我想测试依赖于用户登录的内容 - 我显然不想将上述代码复制到每个需要用户登录的测试中。

就我而言,模拟登录用户只是设置session[:user_id]的情况,所以我在测试中设置会话数据时环顾四周,但这似乎非常棘手。这让我想,也许我可以将上面的代码放在某种可重用的函数中,并从任何需要登录用户的测试中调用它。

这听起来是正确的方法吗? 如果不是,这个问题通常如何解决?

有什么方法可以重用测试代码吗?

迷你测试中的测试只是类。这意味着您可以同时使用经典继承和并行继承(模块混合)。

经典传承

class MyApp::IntegrationTest < ActionDispatch::IntegrationTest
def sign_in(user)
post "/session", user.attributes.slice(%w { username password })
end
end
class FooTest < MyApp::IntegrationTest
setup do
@user = User.create(username: "nick1", password: "password1")
sign_in @user
end
test "can wozzle the fozzle" do
# ...
end
end

混合:

module AuthenticationTestHelper
def sign_in(user)
post "/session", user.attributes.slice(%w { username password })
end
end
class FooTest < ActionDispatch::IntegrationTest
include AuthenticationTestHelper
setup do
@user = User.create(username: "nick1", password: "password1")
sign_in @user
end
test "can wozzle the fozzle" do
# ...
end
end

如果您使用的是 Warden,您可以只包含Warden::Test::Helpers- 如果您不是,您可能应该这样做,而不是重新发明身份验证轮。

最新更新