2014-02-23 18 views
2

我使用Dancer::Plugin::Ajax來定義Dancer中的一些ajax路由。Perl舞者測試:ajax路由沒有route_exists?

get '/' => sub { 
    template 'index' => $data; 
}; 

ajax '/api/foo' => sub { 
    ... 
}; 

ajax '/api/bar' => sub { 
    ... 
}; 

在我的測試,我想測試,如果確實存在的所有路由:

route_exists [GET => '/'], 'a route handler is defined for /'; 
route_exists [AJAX => '/api/foo'], 'an ajax route handler is defined for /api/foo'; 
route_exists [AJAX => '/api/bar'], 'an ajax route handler is defined for /api/bar'; 

但不幸的是不起作用。我也試過

route_exists [GET => '/api/foo'], 'an ajax route handler is defined for /api/foo'; 
route_exists [GET => '/api/bar'], 'an ajax route handler is defined for /api/bar'; 

沒有更迭。

我錯過了文檔中的正確聲明嗎?從 @simbabque第一個答案後


更新:

它幾乎現在的作品。 不幸的是find_route舞者::應用使用

next if $r->has_options && (not $r->validate_options($request)); 

是否會使用

next if $r->has_options && (not $r->check_options($request)); 

一切都將正常工作。 背景是:validate_options舞者::路線只檢查$ _options_aliases,但 所需的選項是 'AJAX' 而這僅僅是在$ _supported_options提及。

想法如何解決這個限制? (我會加我的解決方案,如果這是固定的。)

+0

的'ajax'處理工程通過檢查請求標題。你需要在你的測試中僞造那些。我需要做一些準確的調查。 – simbabque

回答

1

這不是一個完整的答案,只是一個東西,這將幫助你弄明白的集合。

首先,看看https://metacpan.org/source/YANICK/Dancer-1.3121/lib/Dancer/Request.pm#L341is_ajax方法檢查請求是否有$self->{x_requested_with} eq "XMLHttpRequest"

如果你看看https://metacpan.org/source/YANICK/Dancer-1.3121/t/15_plugins/07_ajax_plack_builder.t,這是Ajax插件的測試,它會創建一個新的HTTP :: Request。

我的猜測是你也需要這樣做,以某種方式。查看https://metacpan.org/source/YANICK/Dancer-1.3121/lib/Dancer/Test.pm#L107route_exists並針對ajax請求破解您自己的版本。


更新:

我砍死了一點,但並沒有在所有測試:

*Dancer::Test::ajax_route_exists = sub { 
    my ($req, $test_name) = @_; 
    my $tb = Test::Builder->new; 

    my ($method, $path) = expand_req($req); 
    $test_name ||= "a route exists for $method $path"; 

    $req = Dancer::Request->new_for_request($method => $path, undef, undef, HTTP::Headers->new('X-Requested-With' => 'XMLHttpRequest')); 
    return $tb->ok(defined(Dancer::App->find_route_through_apps($req)), $test_name); 
} 

可能是這個工程算賬:

Dancer::Test::ajax_route_exists [GET => '/api/foo'], 'an ajax route handler is defined for /api/foo'; 
+0

我很匆忙。也許我會在以後玩。還可以在irc.perl.org上的#dancer中詢問。那裏的人會有幫助。 – simbabque

+0

感謝您的想法。 – smartmeta

+0

@smartmeta我增加了一些代碼。 – simbabque