aboutsummaryrefslogtreecommitdiffstats
path: root/spec/controllers/public_body_controller_spec.rb
blob: 5f40127374b96f56d1f4eaafdc91ce039d9f08cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# coding: utf-8
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe PublicBodyController, "when showing a body" do
    integrate_views

    before(:each) do
        load_raw_emails_data
        get_fixtures_xapian_index
    end

    it "should be successful" do
        get :show, :url_name => "dfh", :view => 'all'
        response.should be_success
    end

    it "should render with 'show' template" do
        get :show, :url_name => "dfh", :view => 'all'
        response.should render_template('show')
    end

    it "should assign the body" do
        get :show, :url_name => "dfh", :view => 'all'
        assigns[:public_body].should == public_bodies(:humpadink_public_body)
    end

    it "should assign the requests (1)" do
        get :show, :url_name => "tgq", :view => 'all'
        assigns[:xapian_requests].results.map{|x|x[:model].info_request}.should =~ InfoRequest.all(
            :conditions => ["public_body_id = ?", public_bodies(:geraldine_public_body).id])
    end

    it "should assign the requests (2)" do
        get :show, :url_name => "tgq", :view => 'successful'
        assigns[:xapian_requests].results.map{|x|x[:model].info_request}.should =~ InfoRequest.all(
            :conditions => ["described_state = ? and public_body_id = ?",
                "successful", public_bodies(:geraldine_public_body).id])
    end

    it "should assign the requests (3)" do
        get :show, :url_name => "dfh", :view => 'all'
        assigns[:xapian_requests].results.map{|x|x[:model].info_request}.should =~ InfoRequest.all(
            :conditions => ["public_body_id = ?", public_bodies(:humpadink_public_body).id])
    end

    it "should assign the body using different locale from that used for url_name" do
        PublicBody.with_locale(:es) do
            get :show, {:url_name => "dfh", :view => 'all'}
            assigns[:public_body].notes.should == "Baguette"
        end
    end

    it "should assign the body using same locale as that used in url_name" do
        PublicBody.with_locale(:es) do
            get :show, {:url_name => "edfh", :view => 'all'}
            assigns[:public_body].notes.should == "Baguette"
        end
    end

    it "should redirect use to the relevant locale even when url_name is for a different locale" do
        old_filters = ActionController::Routing::Routes.filters
        ActionController::Routing::Routes.filters = RoutingFilter::Chain.new

        get :show, {:url_name => "edfh", :view => 'all'}
        response.should redirect_to "http://test.host/body/dfh"

        ActionController::Routing::Routes.filters = old_filters
    end

    it "should remember the filter (view) setting on redirecting" do
        get :show, :show_locale => "es", :url_name => "tgq", :view => 'successful'
        response.should redirect_to show_public_body_successful_url(:url_name => "etgq")
    end

    it "should redirect to newest name if you use historic name of public body in URL" do
        get :show, :url_name => "hdink", :view => 'all'
        response.should redirect_to(:controller => 'public_body', :action => 'show', :url_name => "dfh")
    end

    it "should redirect to lower case name if you use mixed case name in URL" do
        get :show, :url_name => "dFh", :view => 'all'
        response.should redirect_to(:controller => 'public_body', :action => 'show', :url_name => "dfh")
    end
end

describe PublicBodyController, "when listing bodies" do
    integrate_views

    it "should be successful" do
        get :list
        response.should be_success
    end

    it "should list all bodies from default locale, even when there are no translations for selected locale" do
        PublicBody.with_locale(:en) do
            @english_only = PublicBody.new(:name => 'English only',
                                          :short_name => 'EO',
                                          :request_email => 'english@flourish.org',
                                          :last_edit_editor => 'test',
                                          :last_edit_comment => '')
            @english_only.save
        end
        PublicBody.with_locale(:es) do
            get :list
            assigns[:public_bodies].include?(@english_only).should == true
        end
    end

    it "should list bodies in alphabetical order" do
        # Note that they are alphabetised by localised name
        get :list

        response.should render_template('list')

        assigns[:public_bodies].should == PublicBody.all(
            :conditions => "id <> #{PublicBody.internal_admin_body.id}",
            :order => "(select name from public_body_translations where public_body_id=public_bodies.id and locale='en')")
        assigns[:tag].should == "all"
        assigns[:description].should == ""
    end

    it "should support simple searching of bodies by title" do
        get :list, :public_body_query => 'quango'
        assigns[:public_bodies].should == [ public_bodies(:geraldine_public_body) ]
    end

    it "should support simple searching of bodies by notes" do
        get :list, :public_body_query => 'Albatross'
        assigns[:public_bodies].should == [ public_bodies(:humpadink_public_body) ]
    end

    it "should list bodies in alphabetical order with different locale" do
        I18n.default_locale = :es
        get :list
        response.should render_template('list')
        assigns[:public_bodies].should == [ public_bodies(:geraldine_public_body), public_bodies(:humpadink_public_body) ]
        assigns[:tag].should == "all"
        assigns[:description].should == ""
        I18n.default_locale = :en
    end

    it "should list a tagged thing on the appropriate list page, and others on the other page, and all still on the all page" do
        load_test_categories

        public_bodies(:humpadink_public_body).tag_string = "foo local_council"

        get :list, :tag => "local_council"
        response.should render_template('list')
        assigns[:public_bodies].should == [ public_bodies(:humpadink_public_body) ]
        assigns[:tag].should == "local_council"
        assigns[:description].should == "in the category ‘Local councils’"

        get :list, :tag => "other"
        response.should render_template('list')
        assigns[:public_bodies].should =~ PublicBody.all(:conditions => "id not in (#{public_bodies(:humpadink_public_body).id}, #{PublicBody.internal_admin_body.id})")

        get :list
        response.should render_template('list')
        assigns[:public_bodies].should =~ PublicBody.all(:conditions => "id <> #{PublicBody.internal_admin_body.id}")
    end

    it "should list a machine tagged thing, should get it in both ways" do
        public_bodies(:humpadink_public_body).tag_string = "eats_cheese:stilton"

        get :list, :tag => "eats_cheese"
        response.should render_template('list')
        assigns[:public_bodies].should == [ public_bodies(:humpadink_public_body) ]
        assigns[:tag].should == "eats_cheese"

        get :list, :tag => "eats_cheese:jarlsberg"
        response.should render_template('list')
        assigns[:public_bodies].should == [ ]
        assigns[:tag].should == "eats_cheese:jarlsberg"

        get :list, :tag => "eats_cheese:stilton"
        response.should render_template('list')
        assigns[:public_bodies].should == [ public_bodies(:humpadink_public_body) ]
        assigns[:tag].should == "eats_cheese:stilton"


    end

end

describe PublicBodyController, "when showing JSON version for API" do

    it "should be successful" do
        get :show, :url_name => "dfh", :format => "json", :view => 'all'

        pb = JSON.parse(response.body)
        pb.class.to_s.should == 'Hash'

        pb['url_name'].should == 'dfh'
        pb['notes'].should == 'An albatross told me!!!'
    end

end

describe PublicBodyController, "when doing type ahead searches" do

    integrate_views

    before(:each) do
        load_raw_emails_data
        get_fixtures_xapian_index
    end

    it "should return nothing for the empty query string" do
        get :search_typeahead, :query => ""
        response.should render_template('public_body/_search_ahead')
        assigns[:xapian_requests].should be_nil
    end

    it "should return a body matching the given keyword, but not users with a matching description" do
        get :search_typeahead, :query => "Geraldine"
        response.should render_template('public_body/_search_ahead')
        response.body.should include('search_ahead')
        assigns[:xapian_requests].results.size.should == 1
        assigns[:xapian_requests].results[0][:model].name.should == public_bodies(:geraldine_public_body).name
    end

    it "should return all requests matching any of the given keywords" do
        get :search_typeahead, :query => "Geraldine Humpadinking"
        response.should render_template('public_body/_search_ahead')
        assigns[:xapian_requests].results.map{|x|x[:model]}.should =~ [
            public_bodies(:humpadink_public_body),
            public_bodies(:geraldine_public_body),
        ]
    end

    it "should return requests matching the given keywords in any of their locales" do
        get :search_typeahead, :query => "baguette" # part of the spanish notes
        response.should render_template('public_body/_search_ahead')
        assigns[:xapian_requests].results.map{|x|x[:model]}.should =~ [public_bodies(:humpadink_public_body)]
    end

    it "should not return  matches for short words" do
        get :search_typeahead, :query => "b"
        response.should render_template('public_body/_search_ahead')
        assigns[:xapian_requests].should be_nil
    end
end
class="w"> page_errors { my $mech = shift; my $result = scraper { process 'div.form-error, p.form-error, p.error, ul.error li', 'errors[]', 'TEXT'; } ->scrape( $mech->response ); my $err = $result->{errors} || []; my %seen = (); $err = [ grep { not $seen{$_}++ } @$err ]; return $err; } =head2 import_errors my $arrayref = $mech->import_errors; Takes the text output from the import post result and returns all the errors as an arrayref. =cut sub import_errors { my $mech = shift; my @errors = # grep { $_ } # map { s{^ERROR:\s*(.*)$}{$1}g ? $_ : undef; } # split m/\n+/, $mech->content; return \@errors; } =head2 pc_alternatives my $arrayref = $mech->pc_alternatives; Find all the suggestions for near matches for a location. Return text presented to user as arrayref, empty arrayref if none found. =cut sub pc_alternatives { my $mech = shift; my $result = scraper { process 'ul.pc_alternatives li', 'pc_alternatives[]', 'TEXT'; } ->scrape( $mech->response ); return $result->{pc_alternatives} || []; } =head2 extract_location $hashref = $mech->extract_location( ); Extracts the location from the current page. Looks for inputs with the names C<pc>, C<latitude> and C<longitude> and returns their values in a hashref with those keys. If no values found then the values in hashrof are C<undef>. =cut sub extract_location { my $mech = shift; my $result = scraper { process 'input[name="pc"]', pc => '@value'; process 'input[name="latitude"]', latitude => '@value'; process 'input[name="longitude"]', longitude => '@value'; } ->scrape( $mech->response ); return { pc => undef, latitude => undef, longitude => undef, %$result }; } =head2 extract_problem_meta $meta = $mech->extract_problem_meta; Returns the problem meta information ( submitted by, at etc ) from a problem report page =cut sub extract_problem_meta { my $mech = shift; my $result = scraper { process 'div#side p em', 'meta', 'TEXT'; process '.problem-header p em', 'meta', 'TEXT'; process '.problem-header p.report_meta_info', 'meta', 'TEXT'; } ->scrape( $mech->response ); my ($meta) = map { s/^\s+//; s/\s+$//; $_; } ($result->{meta}); return $meta; } =head2 extract_problem_title $title = $mech->extract_problem_title; Returns the problem title from a problem report page. =cut sub extract_problem_title { my $mech = shift; my $result = scraper { process 'div#side h1', 'title', 'TEXT'; process '.problem-header h1', 'title', 'TEXT'; } ->scrape( $mech->response ); return $result->{title}; } =head2 extract_problem_banner $banner = $mech->extract_problem_banner; Returns the problem title from a problem report page. Returns a hashref with class and text. =cut sub extract_problem_banner { my $mech = shift; my $result = scraper { process 'div.banner', class => '@class'; process 'div.banner > p', text => 'TEXT'; } ->scrape( $mech->response ); return $result; } =head2 extract_update_metas $metas = $mech->extract_update_metas; Returns an array ref of all the update meta information on the page. Strips whitespace from the start and end of all of them. =cut sub extract_update_metas { my $mech = shift; my $result = scraper { process 'div#updates div.problem-update p em', 'meta[]', 'TEXT'; process '.item-list__update-text .meta-2', 'meta[]', 'TEXT'; } ->scrape( $mech->response ); my @metas = map { s/^\s+//; s/\s+$//; $_; } @{ $result->{meta} }; return \@metas; } =head2 extract_problem_list $problems = $mech->extract_problem_list Returns an array ref of all problem titles on a page featuring standard issue lists =cut sub extract_problem_list { my $mech = shift; my $result = scraper { process 'ul.item-list--reports li a h3', 'problems[]', 'TEXT'; }->scrape( $mech->response ); return $result->{ problems } || []; } =head2 visible_form_values $hashref = $mech->visible_form_values( ); Return all the visible form values on the page - ie not the hidden ones. =cut sub visible_form_values { my $mech = shift; my $name = shift || ''; my $form; if ($name) { for ( $mech->forms ) { $form = $_ if ( $_->attr('name') || '' ) eq $name; } croak "Can't find form named $name - can't continue..." unless $form; } else { my @forms = grep { ( $_->attr('name') || '' ) ne 'overrides_form' } # ignore overrides $mech->forms; croak "Found no forms - can't continue..." unless @forms; croak "Found several forms - don't know which to use..." if @forms > 1; $form = $forms[0]; } my @visible_fields = grep { ref($_) ne 'HTML::Form::SubmitInput' } grep { ref($_) ne 'HTML::Form::ImageInput' } grep { ref($_) ne 'HTML::Form::TextInput' || $_->type ne 'hidden' } grep { !$_->disabled } $form->inputs; my @visible_field_names = map { $_->name } @visible_fields; my %params = map { $_ => $form->value($_) } @visible_field_names; return \%params; } =head2 get_ok_json $decoded = $mech->get_ok_json( $url ); Get the url, check that it was JSON and then decode and return the body. =cut sub get_ok_json { my $mech = shift; my $url = shift; # try to get the response $mech->get_ok($url) || return undef; my $res = $mech->response; # check that the content-type of response is correct croak "Response was not JSON" unless $res->header('Content-Type') =~ m{^application/(?:[a-z]+\+)?json\b}; return decode_json( $res->content ); } sub delete_body { my $mech = shift; my $body = shift; $mech->delete_problems_for_body($body->id); $mech->delete_defect_type($_) for $body->defect_types; $mech->delete_contact($_) for $body->contacts; $mech->delete_user($_) for $body->users; $_->delete for $body->response_templates; $_->delete for $body->response_priorities; $body->body_areas->delete; $body->delete; } sub delete_contact { my $mech = shift; my $contact = shift; $contact->contact_response_templates->delete_all; $contact->contact_response_priorities->delete_all; $contact->delete; } sub delete_problems_for_body { my $mech = shift; my $body = shift; my $reports = FixMyStreet::DB->resultset('Problem')->search( { bodies_str => $body } ); if ( $reports ) { for my $r ( $reports->all ) { $r->comments->delete; $r->questionnaires->delete; } $reports->delete; } } sub delete_defect_type { my $mech = shift; my $defect_type = shift; $defect_type->contact_defect_types->delete_all; $defect_type->delete; } sub delete_response_template { my $mech = shift; my $response_template = shift; $response_template->contact_response_templates->delete_all; $response_template->delete; } sub create_contact_ok { my $self = shift; my %contact_params = ( state => 'confirmed', editor => 'Test', whenedited => \'current_timestamp', note => 'Created for test', @_ ); my $contact = FixMyStreet::DB->resultset('Contact')->find_or_create( \%contact_params ); ok $contact, 'found/created contact ' . $contact->category;; return $contact; } sub create_body_ok { my ( $self, $area_id, $name, $params ) = @_; $params->{name} = $name; my $body = FixMyStreet::DB->resultset('Body'); $body = $body->find_or_create( $params ); ok $body, "found/created body $name"; $body->body_areas->delete; FixMyStreet::DB->resultset('BodyArea')->find_or_create({ area_id => $area_id, body_id => $body->id, }); return $body; } sub create_problems_for_body { my ( $mech, $count, $body, $title, $params ) = @_; my $dt = $params->{dt} || DateTime->now(); my $email = $mech->uniquify_email('test@example.com', (caller)[1]); my $user = $params->{user} || FixMyStreet::DB->resultset('User')->find_or_create( { email => $email, name => 'Test User' } ); delete $params->{user}; delete $params->{dt}; my @problems; while ($count) { my $default_params = { postcode => 'SW1A 1AA', bodies_str => $body, areas => ',105255,11806,11828,2247,2504,', category => 'Other', title => "$title Test $count for $body", detail => "$title Test $count for $body Detail", used_map => 't', name => 'Test User', anonymous => 'f', state => 'confirmed', confirmed => $dt->ymd . ' ' . $dt->hms, lang => 'en-gb', service => '', cobrand => 'default', cobrand_data => '', send_questionnaire => 't', latitude => '51.5016605453401', longitude => '-0.142497580865087', user_id => $user->id, photo => '74e3362283b6ef0c48686fb0e161da4043bbcc97.jpeg', }; my %report_params = ( %$default_params, %$params ); my $problem = FixMyStreet::DB->resultset('Problem')->create( \%report_params ); push @problems, $problem; $count--; } return @problems; } sub create_comment_for_problem { my ( $mech, $problem, $user, $name, $text, $anonymous, $state, $problem_state, $params ) = @_; $params ||= {}; $params->{problem_id} = $problem->id; $params->{user_id} = $user->id; $params->{name} = $name; $params->{text} = $text; $params->{anonymous} = $anonymous; $params->{problem_state} = $problem_state; $params->{state} = $state; $params->{mark_fixed} = $problem_state && FixMyStreet::DB::Result::Problem->fixed_states()->{$problem_state} ? 1 : 0; $params->{confirmed} = \'current_timestamp' unless $params->{confirmed} || $state eq 'unconfirmed'; FixMyStreet::App->model('DB::Comment')->create($params); } sub encoded_content { my $self = shift; return encode_utf8($self->content); } sub content_as_csv { my $self = shift; open my $data_handle, '<:encoding(utf-8)', \$self->encoded_content; my $csv = Text::CSV->new({ binary => 1 }); my @rows; while (my $row = $csv->getline($data_handle)) { push @rows, $row; } return @rows; } 1;