如何使这些测试更加 DRY?
我目前在几个测试文件的开头有以下内容,但它非常不干燥。但我不太确定将其移动到自己的文件中的最佳方法是什么。有什么建议吗?
#!/usr/bin/perl
use strict;
use warnings;
BEGIN {
use Test::More;
use namespace::clean qw( pass );
}
use FindBin;
use Cwd qw( realpath );
use Dancer qw( :syntax );
use Test::WWW::Mechanize::PSGI;
set apphandler => 'PSGI';
my $appdir = realpath( "$FindBin::Bin/.." );
my $t = Test::WWW::Mechanize::PSGI->new(
app => sub {
my $env = shift;
setting(
appname => 'MyApp',
appdir => $appdir,
);
load_app 'MyApp';
config->{environment} = 'test';
Dancer::Config->load;
my $request = Dancer::Request->new( env => $env );
Dancer->dance( $request );
}
);
$t->agent('test');
$t->get_ok('/login') or diag $t->content;
$t->submit_form_ok({
form_name =>'loginform',
fields => {
username => 'myuser',
password => 'foo',
},
}, 'login ok' );
### END BOILERPLATE ###
更新
不幸的是,我将其移至库中的部分问题是,一旦完成,代码就会停止工作。我尝试将其封装到子例程中并返回 $t
但这似乎不起作用。我试图弄清楚什么到底需要进入图书馆以及什么到底需要进入测试。
I currently have the following at the beginning of several test files, but it's very not DRY. But I'm not really sure what the best way to move this into its own file is. Any suggestions?
#!/usr/bin/perl
use strict;
use warnings;
BEGIN {
use Test::More;
use namespace::clean qw( pass );
}
use FindBin;
use Cwd qw( realpath );
use Dancer qw( :syntax );
use Test::WWW::Mechanize::PSGI;
set apphandler => 'PSGI';
my $appdir = realpath( "$FindBin::Bin/.." );
my $t = Test::WWW::Mechanize::PSGI->new(
app => sub {
my $env = shift;
setting(
appname => 'MyApp',
appdir => $appdir,
);
load_app 'MyApp';
config->{environment} = 'test';
Dancer::Config->load;
my $request = Dancer::Request->new( env => $env );
Dancer->dance( $request );
}
);
$t->agent('test');
$t->get_ok('/login') or diag $t->content;
$t->submit_form_ok({
form_name =>'loginform',
fields => {
username => 'myuser',
password => 'foo',
},
}, 'login ok' );
### END BOILERPLATE ###
update
unfortunately part of my problem with moving this off into a library is that as soon as I've done that the code stops working. I tried encapsulating it into a subroutine and returning $t
but that doesn't appear to work. I'm trying to figure out what exactly needs to go into the library and what exactly needs to go into the test.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使其成为一个模块(例如
t::MyApp
),将my $t
更改为our $t
,并让模块导出$t
。 (您还可以编写自定义import
方法来在测试脚本中打开严格和警告。)Make it a module (say
t::MyApp
), changemy $t
toour $t
, and have the module export$t
. (You could also write a customimport
method to turn on strict & warnings in your test script.)您可以创建一个包含这些行的
.pm
模块,并使用一些面向对象的代码从样板代码中获取$t
和其他信息,然后在您的测试中使用
它。You could create a
.pm
module that includes these lines, with some object-oriented code to obtain the$t
and other information from the boilerplate code, and thenuse
it from your tests.