gpt4 book ai didi

ruby-on-rails - Rails 4.2 集成测试 - 有什么方法可以重用测试代码吗?

转载 作者:行者123 更新时间:2023-11-28 21:08:52 25 4
gpt4 key购买 nike

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

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] 的情况,所以我查看了在测试中设置 session 数据,但它看起来非常棘手的。这让我想到也许我可以将上面的代码放在某种可重用的函数中,并从任何需要登录用户的测试中调用它。

这听起来像是正确的方法吗?如果不是,这个问题一般是怎么解决的?

最佳答案

Is there any way to reuse test code?

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

经典传承

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 - 如果你不是,你可能应该而不是重新发明身份验证轮。

关于ruby-on-rails - Rails 4.2 集成测试 - 有什么方法可以重用测试代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43677412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com