diff options
Diffstat (limited to 'spec')
41 files changed, 723 insertions, 680 deletions
diff --git a/spec/controllers/admin_censor_rule_controller_spec.rb b/spec/controllers/admin_censor_rule_controller_spec.rb index 8893a858b..c4860da3f 100644 --- a/spec/controllers/admin_censor_rule_controller_spec.rb +++ b/spec/controllers/admin_censor_rule_controller_spec.rb @@ -1,7 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe AdminCensorRuleController, "when making censor rules from the admin interface" do - integrate_views + render_views before { basic_auth_login @request } it "should create a censor rule and purge the corresponding request from varnish" do diff --git a/spec/controllers/admin_general_controller_spec.rb b/spec/controllers/admin_general_controller_spec.rb index dc1eb0d97..971960762 100644 --- a/spec/controllers/admin_general_controller_spec.rb +++ b/spec/controllers/admin_general_controller_spec.rb @@ -4,7 +4,7 @@ describe AdminGeneralController do describe "when viewing front page of admin interface" do - integrate_views + render_views before { basic_auth_login @request } it "should render the front page" do @@ -14,8 +14,7 @@ describe AdminGeneralController do it "should redirect to include trailing slash" do get :index - response.should redirect_to(:controller => 'admin_general', - :action => 'index') + response.should redirect_to admin_general_index_url(:trailing_slash => true) end end diff --git a/spec/controllers/admin_public_body_controller_spec.rb b/spec/controllers/admin_public_body_controller_spec.rb index 504ddc5cc..3fcc9b36d 100644 --- a/spec/controllers/admin_public_body_controller_spec.rb +++ b/spec/controllers/admin_public_body_controller_spec.rb @@ -1,16 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe AdminPublicBodyController, "when administering public bodies" do - integrate_views - - before do - @old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new - end - - after do - ActionController::Routing::Routes.filters = @old_filters - end + render_views it "shows the index page" do get :index @@ -154,7 +145,7 @@ end describe AdminPublicBodyController, "when administering public bodies and paying attention to authentication" do - integrate_views + render_views before do config = MySociety::Config.load_default() @@ -263,7 +254,7 @@ describe AdminPublicBodyController, "when administering public bodies and paying end describe AdminPublicBodyController, "when administering public bodies with i18n" do - integrate_views + render_views it "shows the index page" do get :index @@ -282,13 +273,13 @@ describe AdminPublicBodyController, "when administering public bodies with i18n" get :edit, {:id => 3, :locale => :en} # When editing a body, the controller returns all available translations - assigns[:public_body].translation("es").name.should == 'El Department for Humpadinking' + assigns[:public_body].find_translation_by_locale("es").name.should == 'El Department for Humpadinking' assigns[:public_body].name.should == 'Department for Humpadinking' response.should render_template('edit') end it "saves edits to a public body" do - PublicBody.with_locale(:es) do + I18n.with_locale(:es) do pb = PublicBody.find(id=3) pb.name.should == "El Department for Humpadinking" post :update, { @@ -308,10 +299,10 @@ describe AdminPublicBodyController, "when administering public bodies with i18n" end pb = PublicBody.find(public_bodies(:humpadink_public_body).id) - PublicBody.with_locale(:es) do + I18n.with_locale(:es) do pb.name.should == "Renamed" end - PublicBody.with_locale(:en) do + I18n.with_locale(:en) do pb.name.should == "Department for Humpadinking" end end @@ -325,16 +316,7 @@ describe AdminPublicBodyController, "when administering public bodies with i18n" end describe AdminPublicBodyController, "when creating public bodies with i18n" do - integrate_views - - before do - @old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new - end - - after do - ActionController::Routing::Routes.filters = @old_filters - end + render_views it "creates a new public body in one locale" do n = PublicBody.count @@ -357,12 +339,12 @@ describe AdminPublicBodyController, "when creating public bodies with i18n" do body = PublicBody.find_by_name("New Quango") body.translations.map {|t| t.locale.to_s}.sort.should == ["en", "es"] - PublicBody.with_locale(:en) do + I18n.with_locale(:en) do body.name.should == "New Quango" body.url_name.should == "new_quango" body.first_letter.should == "N" end - PublicBody.with_locale(:es) do + I18n.with_locale(:es) do body.name.should == "Mi Nuevo Quango" body.url_name.should == "mi_nuevo_quango" body.first_letter.should == "M" diff --git a/spec/controllers/admin_request_controller_spec.rb b/spec/controllers/admin_request_controller_spec.rb index 8a3934685..c9d325b03 100644 --- a/spec/controllers/admin_request_controller_spec.rb +++ b/spec/controllers/admin_request_controller_spec.rb @@ -1,16 +1,11 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe AdminRequestController, "when administering requests" do - integrate_views + render_views before { basic_auth_login @request } before(:each) do load_raw_emails_data - @old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new - end - after do - ActionController::Routing::Routes.filters = @old_filters end it "shows the index/list page" do @@ -82,15 +77,10 @@ describe AdminRequestController, "when administering requests" do end describe AdminRequestController, "when administering the holding pen" do - integrate_views + render_views before(:each) do basic_auth_login @request load_raw_emails_data - @old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new - end - after do - ActionController::Routing::Routes.filters = @old_filters end it "shows a rejection reason for an incoming message from an invalid address" do @@ -100,7 +90,7 @@ describe AdminRequestController, "when administering the holding pen" do ir.save! receive_incoming_mail('incoming-request-plain.email', ir.incoming_email, "frob@nowhere.com") get :show_raw_email, :id => InfoRequest.holding_pen_request.get_last_response.raw_email.id - response.should have_text(/Only the authority can reply to this request/) + response.should contain "Only the authority can reply to this request" end it "allows redelivery even to a closed request" do @@ -164,7 +154,7 @@ describe AdminRequestController, "when administering the holding pen" do receive_incoming_mail('incoming-request-plain.email', ir.incoming_email, "") InfoRequest.holding_pen_request.incoming_messages.length.should == 2 get :show_raw_email, :id => interesting_email - response.should have_text(/Could not identify the request/) + response.should contain "Could not identify the request" assigns[:info_requests][0].should == ir end @@ -236,7 +226,7 @@ describe AdminRequestController, "when administering the holding pen" do :user => nil, :user_name => 'External User', :is_external? => true) - InfoRequest.stub!(:find).with(@info_request.id.to_s).and_return(@info_request) + InfoRequest.stub!(:find).with(@info_request.id).and_return(@info_request) @default_params = { :id => @info_request.id, :explanation => 'Foo', :reason => 'vexatious' } diff --git a/spec/controllers/admin_track_controller_spec.rb b/spec/controllers/admin_track_controller_spec.rb index 728c79f1f..f2de6c0d3 100644 --- a/spec/controllers/admin_track_controller_spec.rb +++ b/spec/controllers/admin_track_controller_spec.rb @@ -1,7 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe AdminTrackController, "when administering tracks" do - integrate_views + render_views it "shows the list page" do get :list diff --git a/spec/controllers/admin_user_controller_spec.rb b/spec/controllers/admin_user_controller_spec.rb index cf3665c9f..a6e5a0d7e 100644 --- a/spec/controllers/admin_user_controller_spec.rb +++ b/spec/controllers/admin_user_controller_spec.rb @@ -1,7 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe AdminUserController, "when administering users" do - integrate_views + render_views it "shows the index/list page" do get :index diff --git a/spec/controllers/api_controller_spec.rb b/spec/controllers/api_controller_spec.rb index 1c320f85c..749be9f85 100644 --- a/spec/controllers/api_controller_spec.rb +++ b/spec/controllers/api_controller_spec.rb @@ -7,7 +7,7 @@ def normalise_whitespace(s) return s end -Spec::Matchers.define :be_equal_modulo_whitespace_to do |expected| +RSpec::Matchers.define :be_equal_modulo_whitespace_to do |expected| match do |actual| normalise_whitespace(actual) == normalise_whitespace(expected) end @@ -173,7 +173,7 @@ describe ApiController, "when using the API" do "body" => "xxx" }.to_json - response.status.should == "500 Internal Server Error" + response.status.should == 500 ActiveSupport::JSON.decode(response.body)["errors"].should == [ "Request #{request_id} cannot be updated using the API"] @@ -195,7 +195,7 @@ describe ApiController, "when using the API" do "body" => "xxx" }.to_json - response.status.should == "500 Internal Server Error" + response.status.should == 500 ActiveSupport::JSON.decode(response.body)["errors"].should == [ "You do not own request #{request_id}"] @@ -213,12 +213,12 @@ describe ApiController, "when using the API" do "body" => "Are you joking, or are you serious?" }.to_json, :attachments => [ - fixture_file_upload("files/tfl.pdf") + fixture_file_upload("/files/tfl.pdf") ] # Make sure it worked - response.status.to_i.should == 500 + response.status.should == 500 errors = ActiveSupport::JSON.decode(response.body)["errors"] errors.should == ["You cannot attach files to messages in the 'request' direction"] end @@ -242,7 +242,7 @@ describe ApiController, "when using the API" do "body" => response_body }.to_json, :attachments => [ - fixture_file_upload("files/tfl.pdf") + fixture_file_upload("/files/tfl.pdf") ] # And make sure it worked @@ -286,7 +286,7 @@ describe ApiController, "when using the API" do :feed_type => "atom" response.should be_success - response.should render_template("api/request_events.atom") + response.should render_template("api/request_events") assigns[:events].size.should > 0 assigns[:events].each do |event| event.info_request.public_body.should == public_bodies(:geraldine_public_body) @@ -341,7 +341,7 @@ describe ApiController, "when using the API" do :feed_type => "atom" response.should be_success - response.should render_template("api/request_events.atom") + response.should render_template("api/request_events") assigns[:events].size.should > 0 assigns[:events].each do |event| event.created_at.should >= Date.new(2010, 1, 1) @@ -360,7 +360,7 @@ describe ApiController, "when using the API" do "sent_at" => sent_at, "body" => response_body }.to_json - response.status.should == "404 Not Found" + response.status.should == 404 ActiveSupport::JSON.decode(response.body)["errors"].should == ["Could not find request 123459876"] end @@ -376,7 +376,7 @@ describe ApiController, "when using the API" do "sent_at" => sent_at, "body" => response_body }.to_json - response.status.should == "500 Internal Server Error" + response.status.should == 500 ActiveSupport::JSON.decode(response.body)["errors"].should == ["Request #{request_id} cannot be updated using the API"] end end diff --git a/spec/controllers/comment_controller_spec.rb b/spec/controllers/comment_controller_spec.rb index 4a7acee23..c03615ce2 100644 --- a/spec/controllers/comment_controller_spec.rb +++ b/spec/controllers/comment_controller_spec.rb @@ -1,7 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe CommentController, "when commenting on a request" do - integrate_views + render_views it "should give an error and render 'new' template when body text is just some whitespace" do post :new, :url_title => info_requests(:naughty_chicken_request).url_title, diff --git a/spec/controllers/general_controller_spec.rb b/spec/controllers/general_controller_spec.rb index 642ed0e05..d4aa034a7 100644 --- a/spec/controllers/general_controller_spec.rb +++ b/spec/controllers/general_controller_spec.rb @@ -12,7 +12,7 @@ describe GeneralController, "when trying to show the blog" do it "should fail silently if the blog is returning an error" do FakeWeb.register_uri(:get, %r|.*|, :body => "Error", :status => ["500", "Error"]) get :blog - response.status.should == "200 OK" + response.status.should == 200 assigns[:blog_items].count.should == 0 end end @@ -35,7 +35,7 @@ end describe GeneralController, "when showing the frontpage" do - integrate_views + render_views before do public_body = mock_model(PublicBody, :name => "Example Public Body", @@ -58,14 +58,14 @@ describe GeneralController, "when showing the frontpage" do it "should render the front page with default language" do get :frontpage - response.should have_tag('html[lang="en"]') + response.should have_selector('html[lang="en"]') end it "should render the front page with default language" do old_default_locale = I18n.default_locale I18n.default_locale = "es" get :frontpage - response.should have_tag('html[lang="es"]') + response.should have_selector('html[lang="es"]') I18n.default_locale = old_default_locale end @@ -77,7 +77,7 @@ describe GeneralController, "when showing the frontpage" do old_default_locale = I18n.default_locale I18n.default_locale = "es" get :frontpage - response.should have_tag('html[lang="es"]') + response.should have_selector('html[lang="es"]') I18n.default_locale = old_default_locale end @@ -87,7 +87,7 @@ describe GeneralController, "when showing the frontpage" do accept_language = "es-ES,en-GB,en-US;q=0.8,en;q=0.6" request.env['HTTP_ACCEPT_LANGUAGE'] = accept_language get :frontpage - response.should have_tag('html[lang="es"]') + response.should have_selector('html[lang="es"]') request.env['HTTP_ACCEPT_LANGUAGE'] = nil end @@ -120,13 +120,13 @@ describe GeneralController, "when showing the frontpage" do it 'should generate URLs without a locale prepended' do get :frontpage - response.should_not have_text(@default_lang_home_link) + response.should_not contain @default_lang_home_link end it 'should render the front page in the default language when no locale param is present and the session locale is not the default' do get(:frontpage, {}, {:locale => 'es'}) - response.should_not have_text(@other_lang_home_link) + response.should_not contain @other_lang_home_link end end @@ -134,7 +134,7 @@ describe GeneralController, "when showing the frontpage" do INCLUDE_DEFAULT_LOCALE_IN_URLS is true' do set_default_locale_in_urls(true) get :frontpage - response.should have_text(@default_lang_home_link) + response.body.should match /#{@default_lang_home_link}/ end after do @@ -150,28 +150,28 @@ describe GeneralController, "when showing the frontpage" do it "should generate URLs with a locale prepended when there's more than one locale set" do get :frontpage - response.should have_text(home_link_regex) + response.body.should match home_link_regex end it "should use our test PO files rather than the application one" do I18n.default_locale = :es get :frontpage - response.should have_text(/XOXO/) + response.body.should match /XOXO/ I18n.default_locale = :en end it "should generate URLs that include the locale when using one that includes an underscore" do I18n.default_locale = :"en_GB" get :frontpage - response.should have_text(/href="\/en_GB\//) + response.body.should match /href="\/en_GB\// I18n.default_locale = :en end it "should fall back to the language if the territory is unknown" do I18n.default_locale = :"en_US" get :frontpage - response.should have_text(/href="\/en\//) - response.should_not have_text(/href="\/en_US\//) + response.body.should match /href="\/en\// + response.body.should_not match /href="\/en_US\// I18n.default_locale = :en end @@ -181,7 +181,7 @@ describe GeneralController, "when showing the frontpage" do FastGettext.default_available_locales = I18n.available_locales = ['en'] get :frontpage - response.should_not have_text(home_link_regex) + response.should_not contain home_link_regex FastGettext.default_available_locales = old_fgt_available_locales I18n.available_locales = old_i18n_available_locales @@ -235,7 +235,7 @@ end describe GeneralController, 'when using xapian search' do - integrate_views + render_views # rebuild xapian index after fixtures loaded before(:each) do @@ -249,7 +249,7 @@ describe GeneralController, 'when using xapian search' do end it "should find info request when searching for '\"fancy dog\"'" do - get :search, :combined => ['"fancy dog"'] + get :search, :combined => '"fancy dog"' response.should render_template('search') assigns[:xapian_requests].matches_estimated.should == 1 assigns[:xapian_requests].results.size.should == 1 @@ -259,7 +259,7 @@ describe GeneralController, 'when using xapian search' do end it "should find public body and incoming message when searching for 'geraldine quango'" do - get :search, :combined => ['geraldine quango'] + get :search, :combined => 'geraldine quango' response.should render_template('search') assigns[:xapian_requests].matches_estimated.should == 1 @@ -272,7 +272,7 @@ describe GeneralController, 'when using xapian search' do end it "should filter results based on end of URL being 'all'" do - get :search, :combined => ['"bob"', "all"] + get :search, :combined => "bob/all" assigns[:xapian_requests].results.map{|x| x[:model]}.should =~ [ info_request_events(:useless_outgoing_message_event), info_request_events(:silly_outgoing_message_event), @@ -284,14 +284,14 @@ describe GeneralController, 'when using xapian search' do end it "should filter results based on end of URL being 'users'" do - get :search, :combined => ['"bob"', "users"] + get :search, :combined => "bob/users" assigns[:xapian_requests].should == nil assigns[:xapian_users].results.map{|x| x[:model]}.should == [users(:bob_smith_user)] assigns[:xapian_bodies].should == nil end it "should filter results based on end of URL being 'requests'" do - get :search, :combined => ['"bob"', "requests"] + get :search, :combined => "bob/requests" assigns[:xapian_requests].results.map{|x|x[:model]}.should =~ [ info_request_events(:useless_outgoing_message_event), info_request_events(:silly_outgoing_message_event), @@ -303,7 +303,7 @@ describe GeneralController, 'when using xapian search' do end it "should filter results based on end of URL being 'bodies'" do - get :search, :combined => ['"quango"', "bodies"] + get :search, :combined => "quango/bodies" assigns[:xapian_requests].should == nil assigns[:xapian_users].should == nil assigns[:xapian_bodies].results.map{|x|x[:model]}.should == [public_bodies(:geraldine_public_body)] @@ -317,7 +317,7 @@ describe GeneralController, 'when using xapian search' do end it "should not show unconfirmed users" do - get :search, :combined => ["unconfirmed", "users"] + get :search, :combined => "unconfirmed/users" response.should render_template('search') assigns[:xapian_users].results.map{|x|x[:model]}.should == [] end @@ -328,13 +328,13 @@ describe GeneralController, 'when using xapian search' do u.save! update_xapian_index - get :search, :combined => ["unconfirmed", "users"] + get :search, :combined => "unconfirmed/users" response.should render_template('search') assigns[:xapian_users].results.map{|x|x[:model]}.should == [u] end it "should show tracking links for requests-only searches" do - get :search, :combined => ['"bob"', "requests"] + get :search, :combined => "bob/requests" response.body.should include('Track this search') end diff --git a/spec/controllers/help_controller_spec.rb b/spec/controllers/help_controller_spec.rb index 28fd08c80..0f6f75eb9 100644 --- a/spec/controllers/help_controller_spec.rb +++ b/spec/controllers/help_controller_spec.rb @@ -1,7 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe HelpController, "when using help" do - integrate_views + render_views it "shows the about page" do get :about diff --git a/spec/controllers/public_body_controller_spec.rb b/spec/controllers/public_body_controller_spec.rb index 29ece18cb..38e874469 100644 --- a/spec/controllers/public_body_controller_spec.rb +++ b/spec/controllers/public_body_controller_spec.rb @@ -2,7 +2,7 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe PublicBodyController, "when showing a body" do - integrate_views + render_views before(:each) do load_raw_emails_data @@ -43,28 +43,23 @@ describe PublicBodyController, "when showing a body" do :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 + it "should redirect to the canonical name in the chosen locale" do + get :show, {:url_name => "dfh", :view => 'all', :show_locale => "es"} + response.should redirect_to "http://test.host/es/body/edfh" 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 + get :show, {:url_name => "edfh", :view => 'all', :show_locale => "es"} + response.should contain("Baguette") 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 + RoutingFilter.active = false get :show, {:url_name => "edfh", :view => 'all'} response.should redirect_to "http://test.host/body/dfh" - ActionController::Routing::Routes.filters = old_filters + RoutingFilter.active = true end it "should redirect to newest name if you use historic name of public body in URL" do @@ -79,7 +74,7 @@ describe PublicBodyController, "when showing a body" do end describe PublicBodyController, "when listing bodies" do - integrate_views + render_views it "should be successful" do get :list @@ -87,7 +82,7 @@ describe PublicBodyController, "when listing bodies" do end it "should list all bodies from default locale, even when there are no translations for selected locale" do - PublicBody.with_locale(:en) do + I18n.with_locale(:en) do @english_only = PublicBody.new(:name => 'English only', :short_name => 'EO', :request_email => 'english@flourish.org', @@ -95,7 +90,7 @@ describe PublicBodyController, "when listing bodies" do :last_edit_comment => '') @english_only.save end - PublicBody.with_locale(:es) do + I18n.with_locale(:es) do get :list assigns[:public_bodies].include?(@english_only).should == true end @@ -107,9 +102,11 @@ describe PublicBodyController, "when listing bodies" do 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[:public_bodies].should == [ public_bodies(:humpadink_public_body), + public_bodies(:forlorn_public_body), + public_bodies(:geraldine_public_body), + public_bodies(:sensible_walks_public_body), + public_bodies(:silly_walks_public_body) ] assigns[:tag].should == "all" assigns[:description].should == "" end @@ -147,11 +144,18 @@ describe PublicBodyController, "when listing bodies" do 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})") + assigns[:public_bodies].should == [ public_bodies(:forlorn_public_body), + public_bodies(:geraldine_public_body), + public_bodies(:sensible_walks_public_body), + public_bodies(:silly_walks_public_body) ] get :list response.should render_template('list') - assigns[:public_bodies].should =~ PublicBody.all(:conditions => "id <> #{PublicBody.internal_admin_body.id}") + assigns[:public_bodies].should == [ public_bodies(:humpadink_public_body), + public_bodies(:forlorn_public_body), + public_bodies(:geraldine_public_body), + public_bodies(:sensible_walks_public_body), + public_bodies(:silly_walks_public_body) ] end it "should list a machine tagged thing, should get it in both ways" do @@ -193,7 +197,7 @@ end describe PublicBodyController, "when doing type ahead searches" do - integrate_views + render_views before(:each) do load_raw_emails_data diff --git a/spec/controllers/request_controller_spec.rb b/spec/controllers/request_controller_spec.rb index 6f25b605a..e9a08e39e 100644 --- a/spec/controllers/request_controller_spec.rb +++ b/spec/controllers/request_controller_spec.rb @@ -2,7 +2,6 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe RequestController, "when listing recent requests" do - before(:each) do load_raw_emails_data get_fixtures_xapian_index @@ -90,7 +89,7 @@ describe RequestController, "when listing recent requests" do end it "should assign the first page of results" do - xap_results = mock_model(ActsAsXapian::Search, + xap_results = mock(ActsAsXapian::Search, :results => (1..25).to_a.map { |m| { :model => m } }, :matches_estimated => 1000000) @@ -103,7 +102,7 @@ describe RequestController, "when listing recent requests" do end it "should return 404 for pages we don't want to serve up" do - xap_results = mock_model(ActsAsXapian::Search, + xap_results = mock(ActsAsXapian::Search, :results => (1..25).to_a.map { |m| { :model => m } }, :matches_estimated => 1000000) lambda { @@ -120,8 +119,7 @@ describe RequestController, "when listing recent requests" do end describe RequestController, "when changing things that appear on the request page" do - - integrate_views + render_views it "should purge the downstream cache when mail is received" do ir = info_requests(:fancy_dog_request) @@ -187,7 +185,7 @@ describe RequestController, "when changing things that appear on the request pag end describe RequestController, "when showing one request" do - integrate_views + render_views before(:each) do load_raw_emails_data @@ -216,20 +214,20 @@ describe RequestController, "when showing one request" do end it "should redirect from a numeric URL to pretty one" do - get :show, :url_title => info_requests(:naughty_chicken_request).id + get :show, :url_title => info_requests(:naughty_chicken_request).id.to_s response.should redirect_to(:action => 'show', :url_title => info_requests(:naughty_chicken_request).url_title) end it 'should show actions the request owner can take' do get :show, :url_title => 'why_do_you_have_such_a_fancy_dog' - response.should have_tag('div#owner_actions') + response.should have_selector('div#owner_actions') end describe 'when the request does allow comments' do it 'should have a comment link' do get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' }, { :user_id => users(:admin_user).id } - response.should have_tag('#anyone_actions', /Add an annotation/) + response.should have_selector('#anyone_actions', :content => "Add an annotation") end end @@ -237,7 +235,7 @@ describe RequestController, "when showing one request" do it 'should not have a comment link' do get :show, { :url_title => 'spam_1' }, { :user_id => users(:admin_user).id } - response.should_not have_tag('#anyone_actions', /Add an annotation/) + response.should_not have_selector('#anyone_actions', :content => "Add an annotation") end end @@ -254,13 +252,13 @@ describe RequestController, "when showing one request" do it 'should show the describe state form' do get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' }, { :user_id => users(:admin_user).id } - response.should have_tag('div.describe_state_form') + response.should have_selector('div.describe_state_form') end it 'should ask the user to use the describe state from' do get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' }, { :user_id => users(:admin_user).id } - response.should have_tag('p#request_status', :text => /answer the question above/) + response.should have_selector('p#request_status', :content => "answer the question above") end end @@ -278,7 +276,7 @@ describe RequestController, "when showing one request" do it 'should give a link to requesting an internal review' do get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' }, { :user_id => users(:admin_user).id } - response.should have_tag('p#request_status', :text =>/requesting an internal review/) + response.should have_selector('p#request_status', :content => "requesting an internal review") end end @@ -296,7 +294,7 @@ describe RequestController, "when showing one request" do it 'should give a link to make a followup' do get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' }, { :user_id => users(:admin_user).id } - response.should have_tag('p#request_status a', :text =>/send a follow up message/) + response.should have_selector('p#request_status a', :content => "send a follow up message") end end @@ -313,7 +311,7 @@ describe RequestController, "when showing one request" do it 'should not display actions the request owner can take' do get :show, :url_title => 'balalas' - response.should_not have_tag('div#owner_actions') + response.should_not have_selector('div#owner_actions') end end @@ -339,12 +337,12 @@ describe RequestController, "when showing one request" do it 'should not show the describe state form' do make_request - response.should_not have_tag('div.describe_state_form') + response.should_not have_selector('div.describe_state_form') end it 'should not ask the user to use the describe state form' do make_request - response.should_not have_tag('p#request_status', :text => /answer the question above/) + response.should_not have_selector('p#request_status', :content => "answer the question above") end end @@ -361,7 +359,7 @@ describe RequestController, "when showing one request" do it 'should not give a link to requesting an internal review' do make_request - response.should_not have_tag('p#request_status', :text =>/requesting an internal review/) + response.should_not have_selector('p#request_status', :content => "requesting an internal review") end end @@ -377,12 +375,12 @@ describe RequestController, "when showing one request" do it 'should not give a link to make a followup' do make_request - response.should_not have_tag('p#request_status a', :text =>/send a follow up message/) + response.should_not have_selector('p#request_status a', :content => "send a follow up message") end it 'should not give a link to sign in (in the request status paragraph)' do make_request - response.should_not have_tag('p#request_status a', :text => /sign in/) + response.should_not have_selector('p#request_status a', :content => "sign in") end end @@ -445,7 +443,7 @@ describe RequestController, "when showing one request" do describe 'when handling incoming mail' do - integrate_views + render_views it "should receive incoming messages, send email to creator, and show them" do ir = info_requests(:fancy_dog_request) @@ -481,11 +479,11 @@ describe RequestController, "when showing one request" do get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1 response.content_type.should == "text/plain" - response.should have_text(/Second hello/) + response.should contain "Second hello" get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 3, :file_name => ['hello.txt'], :skip_cache => 1 response.content_type.should == "text/plain" - response.should have_text(/First hello/) + response.should contain "First hello" end it 'should cache an attachment on a request with normal prominence' do @@ -504,7 +502,7 @@ describe RequestController, "when showing one request" do ir = info_requests(:fancy_dog_request) receive_incoming_mail('iso8859_2_raw_email.email', ir.incoming_email) get :show, :url_title => 'why_do_you_have_such_a_fancy_dog' - response.should have_text(/tënde/u) + response.should contain "tënde" end it "should generate valid HTML verson of plain text attachments" do @@ -513,7 +511,7 @@ describe RequestController, "when showing one request" do ir.reload get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1 response.content_type.should == "text/html" - response.should have_text(/Second hello/) + response.should contain "Second hello" end # This is a regression test for a bug where URLs of this form were causing 500 errors @@ -578,7 +576,7 @@ describe RequestController, "when showing one request" do ir.reload get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['fs_50379341.pdf.html'], :skip_cache => 1 response.content_type.should == "text/html" - response.should have_text(/Walberswick Parish Council/) + response.should contain "Walberswick Parish Council" end it "should not cause a reparsing of the raw email, even when the result would be a 404" do @@ -586,7 +584,7 @@ describe RequestController, "when showing one request" do receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email) ir.reload attachment = IncomingMessage.get_attachment_by_url_part_number(ir.incoming_messages[1].get_attachments_for_display, 2) - attachment.body.should have_text(/Second hello/) + attachment.body.should contain "Second hello" # change the raw_email associated with the message; this only be reparsed when explicitly asked for ir.incoming_messages[1].raw_email.data = ir.incoming_messages[1].raw_email.data.sub("Second", "Third") @@ -598,19 +596,19 @@ describe RequestController, "when showing one request" do }.should raise_error(ActiveRecord::RecordNotFound) attachment = IncomingMessage.get_attachment_by_url_part_number(ir.incoming_messages[1].get_attachments_for_display, 2) - attachment.body.should have_text(/Second hello/) + attachment.body.should contain "Second hello" # ...nor should asking for it by its correct filename... get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1 - response.should_not have_text(/Third hello/) + response.should_not contain "Third hello" # ...but if we explicitly ask for attachments to be extracted, then they should be force = true ir.incoming_messages[1].parse_raw_email!(force) attachment = IncomingMessage.get_attachment_by_url_part_number(ir.incoming_messages[1].get_attachments_for_display, 2) - attachment.body.should have_text(/Second hello/) + attachment.body.should contain "Second hello" get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1 - response.should have_text(/Third hello/) + response.should contain "Third hello" end it "should treat attachments with unknown extensions as binary" do @@ -620,7 +618,7 @@ describe RequestController, "when showing one request" do get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.qwglhm'], :skip_cache => 1 response.content_type.should == "application/octet-stream" - response.should have_text(/an unusual sort of file/) + response.should contain "an unusual sort of file" end it "should not download attachments with wrong file name" do @@ -648,7 +646,7 @@ describe RequestController, "when showing one request" do get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1 response.content_type.should == "text/plain" - response.should have_text(/xxxxxx hello/) + response.should contain "xxxxxx hello" ensure ir.censor_rules.clear end @@ -670,7 +668,7 @@ describe RequestController, "when showing one request" do get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1 response.content_type.should == "text/plain" - response.should have_text(/xxxxxx hello/) + response.should contain "xxxxxx hello" ensure ir.user.censor_rules.clear end @@ -696,7 +694,9 @@ describe RequestController, "when showing one request" do # so at this point, assigns[:info_request].incoming_messages[1].get_attachments_for_display is returning stuff, but the equivalent thing in the template isn't. # but something odd is that the above is return a whole load of attachments which aren't there in the controller - response.body.should have_tag("p.attachment strong", /hello.txt/m) + response.body.should have_selector("p.attachment strong") do |s| + s.should contain /hello.txt/m + end censor_rule = CensorRule.new() censor_rule.text = "hello.txt" @@ -706,7 +706,9 @@ describe RequestController, "when showing one request" do ir.censor_rules << censor_rule begin get :show, :url_title => 'why_do_you_have_such_a_fancy_dog' - response.body.should have_tag("p.attachment strong", /goodbye.txt/m) + response.body.should have_selector("p.attachment strong") do |s| + s.should contain /goodbye.txt/m + end ensure ir.censor_rules.clear end @@ -729,17 +731,17 @@ describe RequestController, "when showing one request" do ir = info_requests(:fancy_dog_request) session[:user_id] = ir.user.id # bob_smith_user get :download_entire_request, :url_title => title - assigns[:url_path].should have_text(/#{title}.zip$/) + assigns[:url_path].should contain /#{title}.zip$/ old_path = assigns[:url_path] - response.location.should have_text(/#{assigns[:url_path]}$/) + response.location.should contain /#{assigns[:url_path]}$/ zipfile = Zip::ZipFile.open(File.join(File.dirname(__FILE__), "../../cache/zips", old_path)) { |zipfile| zipfile.count.should == 1 # just the message } receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email) get :download_entire_request, :url_title => title - assigns[:url_path].should have_text(/#{title}.zip$/) + assigns[:url_path].should contain /#{title}.zip$/ old_path = assigns[:url_path] - response.location.should have_text(/#{assigns[:url_path]}$/) + response.location.should contain /#{assigns[:url_path]}$/ zipfile = Zip::ZipFile.open(File.join(File.dirname(__FILE__), "../../cache/zips", old_path)) { |zipfile| zipfile.count.should == 3 # the message plus two "hello.txt" files } @@ -750,9 +752,9 @@ describe RequestController, "when showing one request" do sleep 1 receive_incoming_mail('incoming-request-attachment-unknown-extension.email', ir.incoming_email) get :download_entire_request, :url_title => title - assigns[:url_path].should have_text(/#{title}.zip$/) + assigns[:url_path].should contain /#{title}.zip$/ assigns[:url_path].should_not == old_path - response.location.should have_text(/#{assigns[:url_path]}/) + response.location.should contain assigns[:url_path] zipfile = Zip::ZipFile.open(File.join(File.dirname(__FILE__), "../../cache/zips", assigns[:url_path])) { |zipfile| zipfile.count.should == 4 # the message, two hello.txt plus the unknown attachment } @@ -762,14 +764,13 @@ describe RequestController, "when showing one request" do info_request = info_requests(:external_request) get :download_entire_request, { :url_title => info_request.url_title }, { :user_id => users(:bob_smith_user) } - response.location.should have_text(/#{assigns[:url_path]}$/) + response.location.should contain /#{assigns[:url_path]}$/ end end end end describe RequestController, "when changing prominence of a request" do - before(:each) do load_raw_emails_data end @@ -851,14 +852,14 @@ describe RequestController, "when changing prominence of a request" do :part => 2, :skip_cache => 1 response.content_type.should == "text/html" - response.should_not have_text(/Second hello/) + response.should_not contain "Second hello" response.should render_template('request/hidden') get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 3, :skip_cache => 1 response.content_type.should == "text/html" - response.should_not have_text(/First hello/) + response.should_not contain "First hello" response.should render_template('request/hidden') response.code.should == '410' end @@ -902,7 +903,6 @@ end # end describe RequestController, "when searching for an authority" do - # Whether or not sign-in is required for this step is configurable, # so we make sure we're logged in, just in case before do @@ -942,7 +942,7 @@ describe RequestController, "when searching for an authority" do end describe RequestController, "when creating a new request" do - integrate_views + render_views before do @user = users(:bob_smith_user) @@ -1178,7 +1178,7 @@ describe RequestController, "when making a new request" do end describe RequestController, "when viewing an individual response for reply/followup" do - integrate_views + render_views before(:each) do load_raw_emails_data @@ -1199,7 +1199,7 @@ describe RequestController, "when viewing an individual response for reply/follo it "should offer the opportunity to reply to the main address" do session[:user_id] = users(:bob_smith_user).id get :show_response, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message) - response.body.should have_tag("div#other_recipients ul li", /the main FOI contact address for/) + response.body.should have_selector("div#other_recipients ul li", :content => "the main FOI contact address for") end it "should offer an opportunity to reply to another address" do @@ -1209,7 +1209,7 @@ describe RequestController, "when viewing an individual response for reply/follo ir.save! receive_incoming_mail('incoming-request-plain.email', ir.incoming_email, "Frob <frob@bonce.com>") get :show_response, :id => ir.id, :incoming_message_id => incoming_messages(:useless_incoming_message) - response.body.should have_tag("div#other_recipients ul li", /Frob/) + response.body.should have_selector("div#other_recipients ul li", :content => "Frob") end it "should not show individual responses if request hidden, even if request owner" do @@ -1479,7 +1479,7 @@ describe RequestController, "when classifying an information request" do deliveries.size.should == 1 mail = deliveries[0] mail.body.should =~ /as needing admin/ - mail.from_addrs.first.to_s.should == @request_owner.name_and_email + mail.from_addrs.first.to_s.should == @request_owner.email end it 'should say it is showing advice as to what to do next' do @@ -1513,11 +1513,10 @@ describe RequestController, "when classifying an information request" do @dog_request = info_requests(:fancy_dog_request) @dog_request.stub!(:each).and_return([@dog_request]) InfoRequest.stub!(:find).and_return(@dog_request) - @old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new + RoutingFilter.active = false end after do - ActionController::Routing::Routes.filters = @old_filters + RoutingFilter.active = true end def request_url @@ -1611,7 +1610,7 @@ describe RequestController, "when classifying an information request" do end describe RequestController, "when sending a followup message" do - integrate_views + render_views before(:each) do load_raw_emails_data @@ -1664,7 +1663,7 @@ describe RequestController, "when sending a followup message" do deliveries.size.should == 1 mail = deliveries[0] mail.body.should =~ /What a useless response! You suck./ - mail.to_addrs.first.to_s.should == "FOI Person <foiperson@localhost>" + mail.to_addrs.first.to_s.should == "foiperson@localhost" response.should redirect_to(:action => 'show', :url_title => info_requests(:fancy_dog_request).url_title) @@ -1693,7 +1692,7 @@ end # it can't check the URLs in the emails I don't think, ugh. describe RequestController, "sending overdue request alerts" do - integrate_views + render_views before(:each) do load_raw_emails_data @@ -1711,9 +1710,9 @@ describe RequestController, "sending overdue request alerts" do mail = chicken_mails[0] mail.body.should =~ /promptly, as normally/ - mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.name_and_email + mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.email - mail.body =~ /(http:\/\/.*\/c\/(.*))/ + mail.body.to_s =~ /(http:\/\/.*\/c\/(.*))/ mail_url = $1 mail_token = $2 @@ -1740,7 +1739,7 @@ describe RequestController, "sending overdue request alerts" do mail = chicken_mails[0] mail.body.should =~ /promptly, as normally/ - mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.name_and_email + mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.email end it "should send not actually send the overdue alert if the user is banned but should @@ -1768,9 +1767,9 @@ describe RequestController, "sending overdue request alerts" do mail = chicken_mails[0] mail.body.should =~ /required by law/ - mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.name_and_email + mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.email - mail.body =~ /(http:\/\/.*\/c\/(.*))/ + mail.body.to_s =~ /(http:\/\/.*\/c\/(.*))/ mail_url = $1 mail_token = $2 @@ -1838,7 +1837,7 @@ describe RequestController, "sending overdue request alerts" do end describe RequestController, "sending unclassified new response reminder alerts" do - integrate_views + render_views before(:each) do load_raw_emails_data @@ -1851,8 +1850,8 @@ describe RequestController, "sending unclassified new response reminder alerts" deliveries.size.should == 3 # sufficiently late it sends reminders too mail = deliveries[0] mail.body.should =~ /To let everyone know/ - mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email - mail.body =~ /(http:\/\/.*\/c\/(.*))/ + mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.email + mail.body.to_s =~ /(http:\/\/.*\/c\/(.*))/ mail_url = $1 mail_token = $2 @@ -1868,7 +1867,7 @@ describe RequestController, "sending unclassified new response reminder alerts" end describe RequestController, "clarification required alerts" do - integrate_views + render_views before(:each) do load_raw_emails_data end @@ -1887,8 +1886,8 @@ describe RequestController, "clarification required alerts" do deliveries.size.should == 1 mail = deliveries[0] mail.body.should =~ /asked you to explain/ - mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email - mail.body =~ /(http:\/\/.*\/c\/(.*))/ + mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.email + mail.body.to_s =~ /(http:\/\/.*\/c\/(.*))/ mail_url = $1 mail_token = $2 @@ -1921,7 +1920,7 @@ describe RequestController, "clarification required alerts" do end describe RequestController, "comment alerts" do - integrate_views + render_views before(:each) do load_raw_emails_data end @@ -1940,8 +1939,8 @@ describe RequestController, "comment alerts" do deliveries = ActionMailer::Base.deliveries mail = deliveries[0] mail.body.should =~ /has annotated your/ - mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email - mail.body =~ /(http:\/\/.*)/ + mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.email + mail.body.to_s =~ /(http:\/\/.*)/ mail_url = $1 mail_url.should match("/request/why_do_you_have_such_a_fancy_dog#comment-#{new_comment.id}") @@ -1990,8 +1989,8 @@ describe RequestController, "comment alerts" do deliveries.size.should == 1 mail = deliveries[0] mail.body.should =~ /There are 2 new annotations/ - mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email - mail.body =~ /(http:\/\/.*)/ + mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.email + mail.body.to_s =~ /(http:\/\/.*)/ mail_url = $1 mail_url.should match("/request/why_do_you_have_such_a_fancy_dog#comment-#{comments(:silly_comment).id}") @@ -2000,7 +1999,7 @@ describe RequestController, "comment alerts" do end describe RequestController, "when viewing comments" do - integrate_views + render_views before(:each) do load_raw_emails_data end @@ -2008,22 +2007,26 @@ describe RequestController, "when viewing comments" do it "should link to the user who submitted it" do session[:user_id] = users(:bob_smith_user).id get :show, :url_title => 'why_do_you_have_such_a_fancy_dog' - response.body.should have_tag("div#comment-1 h2", /Silly.*left an annotation/m) - response.body.should_not have_tag("div#comment-1 h2", /You.*left an annotation/m) + response.body.should have_selector("div#comment-1 h2") do |s| + s.should contain /Silly.*left an annotation/m + s.should_not contain /You.*left an annotation/m + end end it "should link to the user who submitted to it, even if it is you" do session[:user_id] = users(:silly_name_user).id get :show, :url_title => 'why_do_you_have_such_a_fancy_dog' - response.body.should have_tag("div#comment-1 h2", /Silly.*left an annotation/m) - response.body.should_not have_tag("div#comment-1 h2", /You.*left an annotation/m) + response.body.should have_selector("div#comment-1 h2") do |s| + s.should contain /Silly.*left an annotation/m + s.should_not contain /You.*left an annotation/m + end end end describe RequestController, "authority uploads a response from the web interface" do - integrate_views + render_views before(:each) do # domain after the @ is used for authentication of FOI officers, so to test it @@ -2061,7 +2064,7 @@ describe RequestController, "authority uploads a response from the web interface session[:user_id] = @normal_user.id # post up a photo of the parrot - parrot_upload = fixture_file_upload('files/parrot.png','image/png') + parrot_upload = fixture_file_upload('/files/parrot.png','image/png') post :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog', :body => "Find attached a picture of a parrot", :file_1 => parrot_upload, @@ -2089,7 +2092,7 @@ describe RequestController, "authority uploads a response from the web interface session[:user_id] = @foi_officer_user.id # post up a photo of the parrot - parrot_upload = fixture_file_upload('files/parrot.png','image/png') + parrot_upload = fixture_file_upload('/files/parrot.png','image/png') post :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog', :body => "Find attached a picture of a parrot", :file_1 => parrot_upload, @@ -2113,7 +2116,6 @@ describe RequestController, "authority uploads a response from the web interface end describe RequestController, "when showing JSON version for API" do - before(:each) do load_raw_emails_data end @@ -2132,25 +2134,24 @@ describe RequestController, "when showing JSON version for API" do end describe RequestController, "when doing type ahead searches" do - - integrate_views + render_views it "should return nothing for the empty query string" do get :search_typeahead, :q => "" - response.should render_template('request/_search_ahead.rhtml') + response.should render_template('request/_search_ahead') assigns[:xapian_requests].should be_nil end it "should return a request matching the given keyword, but not users with a matching description" do get :search_typeahead, :q => "chicken" - response.should render_template('request/_search_ahead.rhtml') + response.should render_template('request/_search_ahead') assigns[:xapian_requests].results.size.should == 1 assigns[:xapian_requests].results[0][:model].title.should == info_requests(:naughty_chicken_request).title end it "should return all requests matching any of the given keywords" do get :search_typeahead, :q => "money dog" - response.should render_template('request/_search_ahead.rhtml') + response.should render_template('request/_search_ahead') assigns[:xapian_requests].results.map{|x|x[:model].info_request}.should =~ [ info_requests(:fancy_dog_request), info_requests(:naughty_chicken_request), @@ -2160,13 +2161,13 @@ describe RequestController, "when doing type ahead searches" do it "should not return matches for short words" do get :search_typeahead, :q => "a" - response.should render_template('request/_search_ahead.rhtml') + response.should render_template('request/_search_ahead') assigns[:xapian_requests].should be_nil end it "should do partial matches for longer words" do get :search_typeahead, :q => "chick" - response.should render_template('request/_search_ahead.rhtml') + response.should render_template('request/_search_ahead') assigns[:xapian_requests].results.size.should ==1 end @@ -2191,7 +2192,7 @@ describe RequestController, "when doing type ahead searches" do end describe RequestController, "when showing similar requests" do - integrate_views + render_views it "should work" do get :similar, :url_title => info_requests(:badger_request).url_title @@ -2233,7 +2234,7 @@ describe RequestController, "when reporting a request when not logged in" do end describe RequestController, "when reporting a request (logged in)" do - integrate_views + render_views before do @user = users(:robin_user) @@ -2309,7 +2310,6 @@ describe RequestController, "when reporting a request (logged in)" do end describe RequestController, "when caching fragments" do - it "should not fail with long filenames" do long_name = "blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah.txt" info_request = mock(InfoRequest, :user_can_view? => true, diff --git a/spec/controllers/services_controller_spec.rb b/spec/controllers/services_controller_spec.rb index a9950d520..796c6b63d 100644 --- a/spec/controllers/services_controller_spec.rb +++ b/spec/controllers/services_controller_spec.rb @@ -4,7 +4,7 @@ require 'fakeweb' describe ServicesController, "when returning a message for people in other countries" do - integrate_views + render_views # store and restore the locale in the context of the test suite to isolate # changes made in these tests diff --git a/spec/controllers/track_controller_spec.rb b/spec/controllers/track_controller_spec.rb index c785960b5..63192c99e 100644 --- a/spec/controllers/track_controller_spec.rb +++ b/spec/controllers/track_controller_spec.rb @@ -56,7 +56,7 @@ describe TrackController, "when making a new track on a request" do end describe TrackController, "when sending alerts for a track" do - integrate_views + render_views include LinkToHelper # for main_url before(:each) do @@ -66,8 +66,7 @@ describe TrackController, "when sending alerts for a track" do it "should send alerts" do # Don't do clever locale-insertion-unto-URL stuff - old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new + RoutingFilter.active = false # set the time the comment event happened at to within the last week ire = info_request_events(:silly_comment_event) @@ -81,7 +80,7 @@ describe TrackController, "when sending alerts for a track" do mail = deliveries[0] mail.body.should =~ /Alter your subscription/ mail.to_addrs.first.to_s.should include(users(:silly_name_user).email) - mail.body =~ /(http:\/\/.*\/c\/(.*))/ + mail.body.to_s =~ /(http:\/\/.*\/c\/(.*))/ mail_url = $1 mail_token = $2 @@ -115,7 +114,7 @@ describe TrackController, "when sending alerts for a track" do deliveries.size.should == 0 # Restore the routing filters - ActionController::Routing::Routes.filters = old_filters + RoutingFilter.active = true end it "should send localised alerts" do @@ -134,7 +133,7 @@ describe TrackController, "when sending alerts for a track" do end describe TrackController, "when viewing RSS feed for a track" do - integrate_views + render_views before(:each) do load_raw_emails_data @@ -164,7 +163,7 @@ end describe TrackController, "when viewing JSON version of a track feed" do - integrate_views + render_views before(:each) do load_raw_emails_data @@ -206,7 +205,7 @@ end describe TrackController, "when tracking a public body" do - integrate_views + render_views before(:each) do load_raw_emails_data diff --git a/spec/controllers/user_controller_spec.rb b/spec/controllers/user_controller_spec.rb index 23006803b..cfff5c901 100644 --- a/spec/controllers/user_controller_spec.rb +++ b/spec/controllers/user_controller_spec.rb @@ -5,7 +5,7 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') # http://rspec.rubyforge.org/rspec-rails/1.1.12/classes/Spec/Rails/Example/ControllerExampleGroup.html describe UserController, "when showing a user" do - integrate_views + render_views before(:each) do load_raw_emails_data get_fixtures_xapian_index @@ -64,7 +64,7 @@ describe UserController, "when showing a user" do end describe UserController, "when signing in" do - integrate_views + render_views def get_last_postredirect post_redirects = PostRedirect.find_by_sql("select * from post_redirects order by id desc limit 1") @@ -74,7 +74,7 @@ describe UserController, "when signing in" do it "should show sign in / sign up page" do get :signin - response.should have_tag("input#signin_token") + response.should have_selector("input#signin_token") end it "should create post redirect to / when you just go to /signin" do @@ -100,8 +100,7 @@ describe UserController, "when signing in" do end it "should log in when you give right email/password, and redirect to where you were" do - old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new + RoutingFilter.active = false get :signin, :r => "/list" response.should render_template('sign') @@ -112,14 +111,13 @@ describe UserController, "when signing in" do session[:user_id].should == users(:bob_smith_user).id # response doesn't contain /en/ but redirect_to does... response.should redirect_to(:controller => 'request', :action => 'list', :post_redirect => 1) - response.should_not send_email + ActionMailer::Base.deliveries.should be_empty - ActionController::Routing::Routes.filters = old_filters + RoutingFilter.active = true end it "should not log you in if you use an invalid PostRedirect token, and shouldn't give 500 error either" do - old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new + RoutingFilter.active = false post_redirect = "something invalid" lambda { @@ -132,7 +130,7 @@ describe UserController, "when signing in" do response.should render_template('sign') assigns[:post_redirect].should == nil - ActionController::Routing::Routes.filters = old_filters + RoutingFilter.active = true end # No idea how to test this in the test framework :( @@ -152,12 +150,11 @@ describe UserController, "when signing in" do :token => post_redirect.token } response.should render_template('confirm') - response.should send_email + ActionMailer::Base.deliveries.should_not be_empty end it "should confirm your email, log you in and redirect you to where you were after you click an email link" do - old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new + RoutingFilter.active = false get :signin, :r => "/list" post_redirect = get_last_postredirect @@ -165,19 +162,19 @@ describe UserController, "when signing in" do post :signin, { :user_signin => { :email => 'unconfirmed@localhost', :password => 'jonespassword' }, :token => post_redirect.token } - response.should send_email + ActionMailer::Base.deliveries.should_not be_empty deliveries = ActionMailer::Base.deliveries deliveries.size.should == 1 mail = deliveries[0] - mail.body =~ /(http:\/\/.*(\/c\/(.*)))/ + mail.body.to_s =~ /(http:\/\/.*(\/c\/(.*)))/ mail_url = $1 mail_path = $2 mail_token = $3 # check is right confirmation URL mail_token.should == post_redirect.email_token - params_from(:get, mail_path).should == { :controller => 'user', :action => 'confirm', :email_token => mail_token } + Rails.application.routes.recognize_path(mail_path).should == { :controller => 'user', :action => 'confirm', :email_token => mail_token } # check confirmation URL works session[:user_id].should be_nil @@ -185,12 +182,11 @@ describe UserController, "when signing in" do session[:user_id].should == users(:unconfirmed_user).id response.should redirect_to(:controller => 'request', :action => 'list', :post_redirect => 1) - ActionController::Routing::Routes.filters = old_filters + RoutingFilter.active = true end it "should keep you logged in if you click a confirmation link and are already logged in as an admin" do - old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new + RoutingFilter.active = false get :signin, :r => "/list" post_redirect = get_last_postredirect @@ -198,19 +194,19 @@ describe UserController, "when signing in" do post :signin, { :user_signin => { :email => 'unconfirmed@localhost', :password => 'jonespassword' }, :token => post_redirect.token } - response.should send_email + ActionMailer::Base.deliveries.should_not be_empty deliveries = ActionMailer::Base.deliveries deliveries.size.should == 1 mail = deliveries[0] - mail.body =~ /(http:\/\/.*(\/c\/(.*)))/ + mail.body.to_s =~ /(http:\/\/.*(\/c\/(.*)))/ mail_url = $1 mail_path = $2 mail_token = $3 # check is right confirmation URL mail_token.should == post_redirect.email_token - params_from(:get, mail_path).should == { :controller => 'user', :action => 'confirm', :email_token => mail_token } + Rails.application.routes.recognize_path(mail_path).should == { :controller => 'user', :action => 'confirm', :email_token => mail_token } # Log in as an admin session[:user_id] = users(:admin_user).id @@ -222,19 +218,19 @@ describe UserController, "when signing in" do # And the redirect should still work, of course response.should redirect_to(:controller => 'request', :action => 'list', :post_redirect => 1) - ActionController::Routing::Routes.filters = old_filters + RoutingFilter.active = true end end describe UserController, "when signing up" do - integrate_views + render_views it "should be an error if you type the password differently each time" do post :signup, { :user_signup => { :email => 'new@localhost', :name => 'New Person', :password => 'sillypassword', :password_confirmation => 'sillypasswordtwo' } } - assigns[:user_signup].errors[:password].should == 'Please enter the same password twice' + assigns[:user_signup].errors[:password].should == ['Please enter the same password twice'] end it "should be an error to sign up with a misformatted email" do @@ -285,7 +281,7 @@ describe UserController, "when signing up" do end describe UserController, "when signing out" do - integrate_views + render_views it "should log you out and redirect to the home page" do session[:user_id] = users(:bob_smith_user).id @@ -295,21 +291,20 @@ describe UserController, "when signing out" do end it "should log you out and redirect you to where you were" do - old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new + RoutingFilter.active = false session[:user_id] = users(:bob_smith_user).id get :signout, :r => '/list' session[:user_id].should be_nil response.should redirect_to(:controller => 'request', :action => 'list') - ActionController::Routing::Routes.filters = old_filters + RoutingFilter.active = true end end describe UserController, "when sending another user a message" do - integrate_views + render_views it "should redirect to signin page if you go to the contact form and aren't signed in" do get :contact, :id => users(:silly_name_user) @@ -340,13 +335,13 @@ describe UserController, "when sending another user a message" do mail.body.should include("Bob Smith has used #{Configuration::site_name} to send you the message below") mail.body.should include("Just a test!") #mail.to_addrs.first.to_s.should == users(:silly_name_user).name_and_email # XXX fix some nastiness with quoting name_and_email - mail.from_addrs.first.to_s.should == users(:bob_smith_user).name_and_email + mail.from_addrs.first.to_s.should == users(:bob_smith_user).email end end describe UserController, "when changing password" do - integrate_views + render_views it "should show the email form when not logged in" do get :signchangepassword @@ -416,7 +411,7 @@ describe UserController, "when changing password" do end describe UserController, "when changing email address" do - integrate_views + render_views it "should require login" do get :signchangeemail @@ -503,7 +498,7 @@ describe UserController, "when changing email address" do mail.body.should include("confirm that you want to change") mail.to.should == [ 'newbob@localhost' ] - mail.body =~ /(http:\/\/.*(\/c\/(.*)))/ + mail.body.to_s =~ /(http:\/\/.*(\/c\/(.*)))/ mail_url = $1 mail_path = $2 mail_token = $3 @@ -521,7 +516,7 @@ describe UserController, "when changing email address" do post_redirect = PostRedirect.find_by_email_token(mail_token) post_redirect.circumstance.should == 'change_email' post_redirect.user.should == users(:bob_smith_user) - post_redirect.post_params.should == {"submitted_signchangeemail_do"=>"1", + post_redirect.post_params.should == {"submitted_signchangeemail_do"=>1, "action"=>"signchangeemail", "signchangeemail"=>{ "old_email"=>"bob@localhost", @@ -561,7 +556,7 @@ describe UserController, "when changing email address" do end describe UserController, "when using profile photos" do - integrate_views + render_views before do @user = users(:bob_smith_user) @@ -631,7 +626,7 @@ describe UserController, "when showing JSON version for API" do end describe UserController, "when viewing the wall" do - integrate_views + render_views before(:each) do get_fixtures_xapian_index diff --git a/spec/helpers/link_to_helper_spec.rb b/spec/helpers/link_to_helper_spec.rb index 030fd612d..f525c9819 100644 --- a/spec/helpers/link_to_helper_spec.rb +++ b/spec/helpers/link_to_helper_spec.rb @@ -8,11 +8,10 @@ describe LinkToHelper do before do @mock_request = mock_model(InfoRequest, :url_title => 'test_title') - @old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new + RoutingFilter.active = false end after do - ActionController::Routing::Routes.filters = @old_filters + RoutingFilter.active = true end diff --git a/spec/integration/errors_spec.rb b/spec/integration/errors_spec.rb index a44ed7051..0e3157ca8 100644 --- a/spec/integration/errors_spec.rb +++ b/spec/integration/errors_spec.rb @@ -4,26 +4,18 @@ describe "When rendering errors" do before(:each) do load_raw_emails_data - ActionController::Base.consider_all_requests_local = false - end - - after(:each) do - ActionController::Base.consider_all_requests_local = true end it "should render a 404 for unrouteable URLs" do get("/frobsnasm") - response.body.should include("The page doesn't exist") response.code.should == "404" end it "should render a 404 for users that don't exist" do get("/user/wobsnasm") - response.body.should include("The page doesn't exist") response.code.should == "404" end it "should render a 404 for bodies that don't exist" do get("/body/wobsnasm") - response.body.should include("The page doesn't exist") response.code.should == "404" end it "should render a 500 for general errors" do @@ -46,7 +38,6 @@ describe "When rendering errors" do end it "should render a 404 for non-existent 'details' pages for requests" do get("/details/request/wobble" ) - response.body.should include("The page doesn't exist") response.code.should == "404" end end diff --git a/spec/integration/search_request_spec.rb b/spec/integration/search_request_spec.rb index c564032a6..23a62e97b 100644 --- a/spec/integration/search_request_spec.rb +++ b/spec/integration/search_request_spec.rb @@ -13,10 +13,8 @@ describe "When searching" do end it "should redirect requests with search in query string to URL-based page" do - url = '/search/all?query=bob' - request_via_redirect("post", url) - response.request.url.should_not include(url) - response.request.url.should include("/search/bob/all") + post '/search/all?query=bob' + response.should redirect_to "/en/search/bob/all" end it "should correctly execute simple search" do diff --git a/spec/lib/mail_handler/mail_handler_spec.rb b/spec/lib/mail_handler/mail_handler_spec.rb index 48c32e2bc..79b779687 100644 --- a/spec/lib/mail_handler/mail_handler_spec.rb +++ b/spec/lib/mail_handler/mail_handler_spec.rb @@ -22,7 +22,7 @@ describe 'when creating a mail object from raw data' do it 'should convert an iso8859 email to utf8' do mail = get_fixture_mail('iso8859_2_raw_email.email') - mail.subject.should have_text(/gjatë/u) + mail.subject.should match /gjatë/u MailHandler.get_part_body(mail).is_utf8?.should == true end diff --git a/spec/lib/sendmail_return_path_spec.rb b/spec/lib/sendmail_return_path_spec.rb index 137869b6e..b4bdda12c 100644 --- a/spec/lib/sendmail_return_path_spec.rb +++ b/spec/lib/sendmail_return_path_spec.rb @@ -1,5 +1,10 @@ # This is a test of the monkey patches in sendmail_return_path.rb +# In Rails 3 the monkeypatches are not needed anymore because sendmail now has the "-f" flag +# set correctly. So, strictly these tests are testing the Rails internals. So, that means we really +# should delete them. Let's do that later when things have settled down. For the time being leave +# them in + require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe "when sending email with an altered return path" do @@ -40,7 +45,7 @@ describe "when sending email with an altered return path" do it "should set the return path when sending email using sendmail" do with_stub_popen do - IO.should_receive(:popen).once.with('/usr/sbin/sendmail -i -t -f "test@localhost"', "w+") + IO.should_receive(:popen).once.with('/usr/sbin/sendmail -i -t -f "test@localhost" postmaster@localhost', "w+") with_delivery_method :sendmail do ContactMailer.deliver_to_admin_message( "Mr. Test", "test@localhost", "Test script spec/lib/sendmail_return_path_spec.rb", diff --git a/spec/lib/timezone_fixes_spec.rb b/spec/lib/timezone_fixes_spec.rb index 9d6ade526..8a9a3bf31 100644 --- a/spec/lib/timezone_fixes_spec.rb +++ b/spec/lib/timezone_fixes_spec.rb @@ -3,6 +3,11 @@ # We use MailServerLogDone here just as a totally random model that has a datetime type. require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') +# In Rails 3 the monkeypatch that these tests are testing is not necessary. So, +# since these tests are testing the Rails internals you could argue that they shouldn't +# be here. Well, you're right. But let's leave them in for the time being until the upgrade is finished. +# Then, we should probably delete this whole file + describe "when doing things with timezones" do it "should preserve time objects with local time conversion to default timezone UTC diff --git a/spec/models/application_mailer_spec.rb b/spec/models/application_mailer_spec.rb index acf5f43bc..cc4609e5a 100644 --- a/spec/models/application_mailer_spec.rb +++ b/spec/models/application_mailer_spec.rb @@ -8,8 +8,7 @@ describe ApplicationMailer do def set_base_views ApplicationMailer.class_eval do @previous_view_paths = self.view_paths.dup - self.view_paths.clear - self.view_paths << File.join(Rails.root, 'spec', 'fixtures', 'theme_views', 'core') + self.view_paths = [File.join(Rails.root, 'spec', 'fixtures', 'theme_views', 'core')] end end @@ -27,13 +26,13 @@ describe ApplicationMailer do def prepend_theme_views(theme_name) ApplicationMailer.class_eval do - view_paths.unshift File.join(Rails.root, 'spec', 'fixtures', 'theme_views', theme_name) + prepend_view_path File.join(Rails.root, 'spec', 'fixtures', 'theme_views', theme_name) end end def append_theme_views(theme_name) ApplicationMailer.class_eval do - view_paths << File.join(Rails.root, 'spec', 'fixtures', 'theme_views', theme_name) + append_view_path File.join(Rails.root, 'spec', 'fixtures', 'theme_views', theme_name) end end @@ -45,11 +44,8 @@ describe ApplicationMailer do def create_multipart_method(method_name) ApplicationMailer.send(:define_method, method_name) do - attachment :content_type => 'message/rfc822', - :body => 'xxx', - :filename => "original.eml", - :transfer_encoding => '7bit', - :content_disposition => 'inline' + attachments['original.eml'] = 'xxx' + mail end end @@ -78,10 +74,10 @@ describe ApplicationMailer do @mail.body.should match('Core only') end - it 'should raise an error if the template is in neither core nor theme' do + it 'should render an empty body if the template is in neither core nor theme' do prepend_theme_views('theme_one') - expected_error = 'Missing template application_mailer/neither.erb in view path' - lambda{ ApplicationMailer.create_neither() }.should raise_error(/#{expected_error}/) + @mail = ApplicationMailer.create_neither() + @mail.body.should be_empty end it 'should render a multipart email using a theme template' do @@ -124,10 +120,10 @@ describe ApplicationMailer do @mail.body.should match('Core only') end - it 'should raise an error if the template is in neither core nor theme' do + it 'should render an empty body if the template is in neither core nor theme' do append_theme_views('theme_one') - expected_error = 'Missing template application_mailer/neither.erb in view path' - lambda{ ApplicationMailer.create_neither() }.should raise_error(/#{expected_error}/) + @mail = ApplicationMailer.create_neither() + @mail.body.should be_empty end it 'should render a multipart email using a core template' do diff --git a/spec/models/censor_rule_spec.rb b/spec/models/censor_rule_spec.rb index c11b05a03..3782cc630 100644 --- a/spec/models/censor_rule_spec.rb +++ b/spec/models/censor_rule_spec.rb @@ -73,10 +73,10 @@ end describe 'when validating rules' do - describe 'should be invalid without text' do + it 'should be invalid without text' do censor_rule = CensorRule.new censor_rule.valid?.should == false - censor_rule.errors.on(:text).should == "can't be blank" + censor_rule.errors[:text].should == ["can't be blank"] end describe 'when validating a regexp rule' do @@ -96,7 +96,7 @@ describe 'when validating rules' do it 'should add an error message to the text field with the regexp error message' do Regexp.stub!(:new).and_raise(RegexpError.new("very bad regexp")) @censor_rule.valid?.should == false - @censor_rule.errors.on(:text).should == "very bad regexp" + @censor_rule.errors[:text].should == ["very bad regexp"] end end @@ -106,7 +106,7 @@ describe 'when validating rules' do it 'should not add any error message to the text field' do Regexp.stub!(:new) @censor_rule.valid? - @censor_rule.errors.on(:text).should == nil + @censor_rule.errors[:text].should == [] end end @@ -134,15 +134,21 @@ describe 'when validating rules' do it 'should not allow a global text censor rule (without user_id, request_id or public_body_id)' do @censor_rule.valid?.should == false - @expected_error = 'Censor must apply to an info request a user or a body; is invalid' - @censor_rule.errors.full_messages.should == [@expected_error] + + expected_error = ["Rule must apply to an info request, a user or a body"] + @censor_rule.errors[:user].should == expected_error + @censor_rule.errors[:info_request].should == expected_error + @censor_rule.errors[:public_body].should == expected_error end it 'should not allow a global regex censor rule (without user_id, request_id or public_body_id)' do @censor_rule.regexp = true @censor_rule.valid?.should == false - @expected_error = 'Censor must apply to an info request a user or a body; is invalid' - @censor_rule.errors.full_messages.should == [@expected_error] + + expected_error = ["Rule must apply to an info request, a user or a body"] + @censor_rule.errors[:user].should == expected_error + @censor_rule.errors[:info_request].should == expected_error + @censor_rule.errors[:public_body].should == expected_error end end diff --git a/spec/models/incoming_message_spec.rb b/spec/models/incoming_message_spec.rb index f53a5856a..781212841 100644 --- a/spec/models/incoming_message_spec.rb +++ b/spec/models/incoming_message_spec.rb @@ -27,7 +27,7 @@ describe IncomingMessage, " when dealing with incoming mail" do end it "should correctly fold various types of footer" do - Dir.glob(File.join(Spec::Runner.configuration.fixture_path, "files", "email-folding-example-*.txt")).each do |file| + Dir.glob(File.join(RSpec.configuration.fixture_path, "files", "email-folding-example-*.txt")).each do |file| message = File.read(file) parsed = IncomingMessage.remove_quoted_sections(message) expected = File.read("#{file}.expected") diff --git a/spec/models/info_request_event_spec.rb b/spec/models/info_request_event_spec.rb index 796f8b840..842246fd8 100644 --- a/spec/models/info_request_event_spec.rb +++ b/spec/models/info_request_event_spec.rb @@ -21,7 +21,7 @@ describe InfoRequestEvent do :event_type => 'sent', :params => {}) event.should_receive(:xapian_mark_needs_index) - event.run_callbacks(:after_save) + event.run_callbacks(:save) end end diff --git a/spec/models/info_request_spec.rb b/spec/models/info_request_spec.rb index 544852f91..a1a6e6c27 100644 --- a/spec/models/info_request_spec.rb +++ b/spec/models/info_request_spec.rb @@ -426,8 +426,8 @@ describe InfoRequest do before do Time.stub!(:now).and_return(Time.utc(2007, 11, 9, 23, 59)) - @mock_comment_event = safe_mock_model(InfoRequestEvent, :created_at => Time.now - 23.days, :event_type => 'comment') - @mock_response_event = safe_mock_model(InfoRequestEvent, :created_at => Time.now - 22.days, :event_type => 'response') + @mock_comment_event = mock_model(InfoRequestEvent, :created_at => Time.now - 23.days, :event_type => 'comment') + @mock_response_event = mock_model(InfoRequestEvent, :created_at => Time.now - 22.days, :event_type => 'response') @info_request = InfoRequest.new(:prominence => 'normal', :awaiting_description => true, :info_request_events => [@mock_response_event, @mock_comment_event]) @@ -457,16 +457,16 @@ describe InfoRequest do describe 'when applying censor rules' do before do - @global_rule = safe_mock_model(CensorRule, :apply_to_text! => nil, + @global_rule = mock_model(CensorRule, :apply_to_text! => nil, :apply_to_binary! => nil) - @user_rule = safe_mock_model(CensorRule, :apply_to_text! => nil, + @user_rule = mock_model(CensorRule, :apply_to_text! => nil, :apply_to_binary! => nil) - @request_rule = safe_mock_model(CensorRule, :apply_to_text! => nil, + @request_rule = mock_model(CensorRule, :apply_to_text! => nil, :apply_to_binary! => nil) - @body_rule = safe_mock_model(CensorRule, :apply_to_text! => nil, + @body_rule = mock_model(CensorRule, :apply_to_text! => nil, :apply_to_binary! => nil) - @user = safe_mock_model(User, :censor_rules => [@user_rule]) - @body = safe_mock_model(PublicBody, :censor_rules => [@body_rule]) + @user = mock_model(User, :censor_rules => [@user_rule]) + @body = mock_model(PublicBody, :censor_rules => [@body_rule]) @info_request = InfoRequest.new(:prominence => 'normal', :awaiting_description => true, :title => 'title') diff --git a/spec/models/public_body_spec.rb b/spec/models/public_body_spec.rb index c2e0a6353..bc693b4da 100644 --- a/spec/models/public_body_spec.rb +++ b/spec/models/public_body_spec.rb @@ -169,6 +169,14 @@ describe PublicBody, " when saving" do @public_body.save! @public_body.first_letter.should == 'T' end + + it "should save the name when renaming an existing public body" do + public_body = public_bodies(:geraldine_public_body) + public_body.name = "Mark's Public Body" + public_body.save! + + public_body.name.should == "Mark's Public Body" + end end describe PublicBody, "when searching" do @@ -210,7 +218,7 @@ describe PublicBody, "when searching" do end it "should cope with same url_name across multiple locales" do - PublicBody.with_locale(:es) do + I18n.with_locale(:es) do # use the unique spanish name to retrieve and edit body = PublicBody.find_by_url_name_with_historic('etgq') body.short_name = 'tgq' # Same as english version @@ -231,7 +239,7 @@ end describe PublicBody, " when dealing public body locales" do it "shouldn't fail if it internal_admin_body was created in a locale other than the default" do # first time, do it with the non-default locale - PublicBody.with_locale(:es) do + I18n.with_locale(:es) do PublicBody.internal_admin_body end @@ -378,7 +386,7 @@ describe PublicBody, " when loading CSV files" do PublicBody.count.should == original_count + 3 - # XXX Not sure why trying to do a PublicBody.with_locale fails here. Seems related to + # XXX Not sure why trying to do a I18n.with_locale fails here. Seems related to # the way categories are loaded every time from the PublicBody class. For now we just # test some translation was done. body = PublicBody.find_by_name('North West Fake Authority') diff --git a/spec/models/request_mailer_spec.rb b/spec/models/request_mailer_spec.rb index 5edc8edb6..72fd808d7 100644 --- a/spec/models/request_mailer_spec.rb +++ b/spec/models/request_mailer_spec.rb @@ -98,7 +98,7 @@ describe RequestMailer, " when receiving incoming mail" do mail.multipart?.should == true mail.parts.size.should == 2 message_part = mail.parts[0].to_s - bounced_mail = MailHandler.mail_from_raw_email(mail.parts[1].body) + bounced_mail = MailHandler.mail_from_raw_email(mail.parts[1].body.to_s) bounced_mail.to.should == [ ir.incoming_email ] bounced_mail.from.should == [ 'geraldinequango@localhost' ] bounced_mail.body.include?("That's so totally a rubbish question").should be_true @@ -243,7 +243,7 @@ describe RequestMailer, "when sending reminders to requesters to classify a resp query_params[:conditions].should == expected_conditions query_params[:include].should == [ :user ] query_params[:order].should == 'info_requests.id' - end + end.and_return [@mock_request] send_alerts end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index e31c3f1b5..651ba4b65 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -152,10 +152,10 @@ end describe User, "when reindexing referencing models" do before do - @request_event = safe_mock_model(InfoRequestEvent, :xapian_mark_needs_index => true) - @request = safe_mock_model(InfoRequest, :info_request_events => [@request_event]) - @comment_event = safe_mock_model(InfoRequestEvent, :xapian_mark_needs_index => true) - @comment = safe_mock_model(Comment, :info_request_events => [@comment_event]) + @request_event = mock_model(InfoRequestEvent, :xapian_mark_needs_index => true) + @request = mock_model(InfoRequest, :info_request_events => [@request_event]) + @comment_event = mock_model(InfoRequestEvent, :xapian_mark_needs_index => true) + @comment = mock_model(Comment, :info_request_events => [@comment_event]) @user = User.new(:comments => [@comment], :info_requests => [@request]) end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 561a75da6..777948c6b 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,35 +1,30 @@ -# This file is copied to ~/spec when you run 'ruby script/generate rspec' -# from the project root directory. -ENV["RAILS_ENV"] = 'test' -require File.expand_path(File.join('..', '..', 'config', 'environment'), __FILE__) -require 'spec/autorun' -require 'spec/rails' +# This file is copied to spec/ when you run 'rails generate rspec:install' +ENV["RAILS_ENV"] ||= 'test' +require File.expand_path("../../config/environment", __FILE__) +require 'rspec/rails' +require 'rspec/autorun' -# set a default username and password so we can test -config = MySociety::Config.load_default() -config['ADMIN_USERNAME'] = 'foo' -config['ADMIN_PASSWORD'] = 'baz' - -# tests assume 20 days -config['REPLY_LATE_AFTER_DAYS'] = 20 - -# register a fake Varnish server -require 'fakeweb' -FakeWeb.register_uri(:purge, %r|varnish.localdomain|, :body => "OK") - -# Uncomment the next line to use webrat's matchers -#require 'webrat/integrations/rspec-rails' +# Requires supporting ruby files with custom matchers and macros, etc, +# in spec/support/ and its subdirectories. +Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} # Use test-specific translations FastGettext.add_text_domain 'app', :path => File.join(File.dirname(__FILE__), 'fixtures', 'locale'), :type => :po FastGettext.default_text_domain = 'app' -Spec::Runner.configure do |config| - # If you're not using ActiveRecord you should remove these - # lines, delete config/database.yml and disable :active_record - # in your config/boot.rb - # fixture_path must end in a separator - config.fixture_path = File.join(Rails.root, 'spec', 'fixtures') + File::SEPARATOR +RSpec.configure do |config| + # ## Mock Framework + # + # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: + # + # config.mock_with :mocha + # config.mock_with :flexmock + # config.mock_with :rr + + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_path = "#{::Rails.root}/spec/fixtures" + + # The order (!) of this is important thanks to foreign keys config.global_fixtures = :users, :public_bodies, :public_body_translations, @@ -46,118 +41,37 @@ Spec::Runner.configure do |config| :holidays, :track_things_sent_emails - # This section makes the garbage collector run less often to speed up tests - last_gc_run = Time.now + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = true - config.before(:each) do - GC.disable - end + # If true, the base class of anonymous controllers will be inferred + # automatically. This will be the default behavior in future versions of + # rspec-rails. + config.infer_base_class_for_anonymous_controllers = false + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + #config.order = "random" - config.after(:each) do - if Time.now - last_gc_run > 4 - GC.enable - GC.start - last_gc_run = Time.now - end + # This is a workaround for a strange thing where ActionMailer::Base.deliveries isn't being + # cleared out correctly in controller specs. So, do it here for everything. + config.before(:each) do + ActionMailer::Base.deliveries = [] end - # == Fixtures - # - # You can declare fixtures for each example_group like this: - # describe "...." do - # fixtures :table_a, :table_b - # - # Alternatively, if you prefer to declare them only once, you can - # do so right here. Just uncomment the next line and replace the fixture - # names with your fixtures. - # - # config.global_fixtures = :table_a, :table_b - # - # If you declare global fixtures, be aware that they will be declared - # for all of your examples, even those that don't use them. - # - # You can also declare which fixtures to use (for example fixtures for test/fixtures): - # - # config.fixture_path = Rails.root + '/spec/fixtures/' - # - # == Mock Framework - # - # RSpec uses its own mocking framework by default. If you prefer to - # use mocha, flexmock or RR, uncomment the appropriate line: - # - # config.mock_with :mocha - # config.mock_with :flexmock - # config.mock_with :rr - # - # == Notes - # - # For more information take a look at Spec::Runner::Configuration and Spec::Runner end # XXX No idea what namespace/class/module to put this in -def receive_incoming_mail(email_name, email_to, email_from = 'geraldinequango@localhost') - email_name = file_fixture_name(email_name) - content = File.read(email_name) - content.gsub!('EMAIL_TO', email_to) - content.gsub!('EMAIL_FROM', email_from) - RequestMailer.receive(content) -end - -def file_fixture_name(file_name) - return File.join(Spec::Runner.configuration.fixture_path, "files", file_name) -end - -def load_file_fixture(file_name, as_binary=false) - file_name = file_fixture_name(file_name) - content = File.open(file_name, 'r') do |file| - if as_binary - file.set_encoding(Encoding::BINARY) if file.respond_to?(:set_encoding) - end - file.read - end - return content -end - -def parse_all_incoming_messages - IncomingMessage.find(:all).each{ |x| x.parse_raw_email! } -end - -def load_raw_emails_data - raw_emails_yml = File.join(Spec::Runner.configuration.fixture_path, "raw_emails.yml") - for raw_email_id in YAML::load_file(raw_emails_yml).map{|k,v| v["id"]} do - raw_email = RawEmail.find(raw_email_id) - raw_email.data = load_file_fixture("raw_emails/%d.email" % [raw_email_id]) - end -end - -# Rebuild the current xapian index -def rebuild_xapian_index(terms = true, values = true, texts = true, dropfirst = true) - if dropfirst - begin - ActsAsXapian.readable_init - FileUtils.rm_r(ActsAsXapian.db_path) - rescue RuntimeError - end - ActsAsXapian.writable_init - ActsAsXapian.writable_db.close - end - parse_all_incoming_messages - # safe_rebuild=true, which involves forking to avoid memory leaks, doesn't work well with rspec. - # unsafe is significantly faster, and we can afford possible memory leaks while testing. - models = [PublicBody, User, InfoRequestEvent] - ActsAsXapian.rebuild_index(models, verbose=false, terms, values, texts, safe_rebuild=false) -end - # Create a clean xapian index based on the fixture files and the raw_email data. def create_fixtures_xapian_index load_raw_emails_data rebuild_xapian_index end -def update_xapian_index - ActsAsXapian.update_index(flush_to_disk=false, verbose=false) -end - # Copy the xapian index created in create_fixtures_xapian_index to a temporary # copy at the same level and point xapian at the copy def get_fixtures_xapian_index() @@ -173,86 +87,18 @@ def get_fixtures_xapian_index() ActsAsXapian.db_path = temp_path end -# Validate an entire HTML page -def validate_html(html) - $tempfilecount = $tempfilecount + 1 - tempfilename = File.join(Dir::tmpdir, "railshtmlvalidate."+$$.to_s+"."+$tempfilecount.to_s+".html") - File.open(tempfilename, "w+") do |f| - f.puts html - end - if not system($html_validation_script, *($html_validation_script_options +[tempfilename])) - raise "HTML validation error in " + tempfilename + " HTTP status: " + @response.response_code.to_s - end - File.unlink(tempfilename) - return true -end - -# Validate HTML fragment by wrapping it as the <body> of a page -def validate_as_body(html) - validate_html('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' + - "<html><head><title>Test</title></head><body>#{html}</body></html>") -end - -def basic_auth_login(request, username = nil, password = nil) - username = Configuration::admin_username if username.nil? - password = Configuration::admin_password if password.nil? - request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("#{username}:#{password}") -end - -# Monkeypatch! Validate HTML in tests. -$html_validation_script_found = false -Configuration::utility_search_path.each do |d| - $html_validation_script = File.join(d, "validate") - $html_validation_script_options = ["--charset=utf-8"] - if File.file? $html_validation_script and File.executable? $html_validation_script - $html_validation_script_found = true - break - end -end -if $tempfilecount.nil? - $tempfilecount = 0 - if $html_validation_script_found - module ActionController - module TestProcess - # Hook into the process function, so can automatically get HTML after each request - alias :original_process :process - def is_fragment - # XXX there must be a better way of doing this! - return @request.query_parameters["action"] == "search_typeahead" - end - def process(action, parameters = nil, session = nil, flash = nil, http_method = 'GET') - self.original_process(action, parameters, session, flash, http_method) - # don't validate auto-generated HTML - return if @request.query_parameters["action"] == "get_attachment_as_html" - # XXX Is there a better way to check this than calling a private method? - return unless @response.template.controller.instance_eval { integrate_views? } - # And then if HTML, not a redirect (302, 301) - if @response.content_type == "text/html" && ! [301,302,401].include?(@response.response_code) - if !is_fragment - validate_html(@response.body) - else - # it's a partial - validate_as_body(@response.body) - end - end - end - end - end - else - puts "WARNING: HTML validation script " + $html_validation_script + " not found" - end -end - -# to_ary differs in Ruby 1.8 and 1.9 -# @see http://yehudakatz.com/2010/01/02/the-craziest-fing-bug-ive-ever-seen/ -def safe_mock_model(model, args = {}) - mock = mock_model(model, args) - mock.should_receive(:to_ary).any_number_of_times - mock +def with_env_tz(new_tz = 'US/Eastern') + old_tz, ENV['TZ'] = ENV['TZ'], new_tz + yield +ensure + old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') end -def get_fixture_mail(filename) - MailHandler.mail_from_raw_email(load_file_fixture(filename)) +def with_active_record_default_timezone(zone) + old_zone, ActiveRecord::Base.default_timezone = ActiveRecord::Base.default_timezone, zone + yield +ensure + ActiveRecord::Base.default_timezone = old_zone end def load_test_categories @@ -263,30 +109,9 @@ def load_test_categories [ "other", "Miscellaneous", "miscellaneous" ],]) end - -# Monkeypatch applicationcontroller because the `render_to_string` -# method in the original breaks all the rspec test assertions such as -# `should render_template('foo')`. Same problem as -# http://stackoverflow.com/questions/8174415/is-it-possible-to-assert-template-or-render-template-against-the-same-partial-wi -# - a bug in either Rails or Rspec I don't have the time to fix :( - -class ApplicationController < ActionController::Base - def set_popup_banner - @popup_banner = nil - end -end - - -def with_env_tz(new_tz = 'US/Eastern') - old_tz, ENV['TZ'] = ENV['TZ'], new_tz - yield -ensure - old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') +def basic_auth_login(request, username = nil, password = nil) + username = Configuration::admin_username if username.nil? + password = Configuration::admin_password if password.nil? + request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("#{username}:#{password}") end -def with_active_record_default_timezone(zone) - old_zone, ActiveRecord::Base.default_timezone = ActiveRecord::Base.default_timezone, zone - yield -ensure - ActiveRecord::Base.default_timezone = old_zone -end diff --git a/spec/spec_helper.rb.rails2 b/spec/spec_helper.rb.rails2 new file mode 100644 index 000000000..aee3ce122 --- /dev/null +++ b/spec/spec_helper.rb.rails2 @@ -0,0 +1,129 @@ +# This file is copied to ~/spec when you run 'ruby script/generate rspec' +# from the project root directory. +ENV["RAILS_ENV"] = 'test' +require File.expand_path(File.join('..', '..', 'config', 'environment'), __FILE__) +require 'spec/autorun' +require 'spec/rails' + +# set a default username and password so we can test +config = MySociety::Config.load_default() +config['ADMIN_USERNAME'] = 'foo' +config['ADMIN_PASSWORD'] = 'baz' + +# tests assume 20 days +config['REPLY_LATE_AFTER_DAYS'] = 20 + +# register a fake Varnish server +require 'fakeweb' +FakeWeb.register_uri(:purge, %r|varnish.localdomain|, :body => "OK") + +# Uncomment the next line to use webrat's matchers +#require 'webrat/integrations/rspec-rails' + +Spec::Runner.configure do |config| + # If you're not using ActiveRecord you should remove these + # lines, delete config/database.yml and disable :active_record + # in your config/boot.rb + + # fixture_path must end in a separator + config.fixture_path = File.join(Rails.root, 'spec', 'fixtures') + File::SEPARATOR + config.global_fixtures = :users, + :public_bodies, + :public_body_translations, + :public_body_versions, + :info_requests, + :raw_emails, + :incoming_messages, + :outgoing_messages, + :comments, + :info_request_events, + :track_things, + :foi_attachments, + :has_tag_string_tags, + :holidays, + :track_things_sent_emails + + # This section makes the garbage collector run less often to speed up tests + last_gc_run = Time.now + + config.before(:each) do + GC.disable + end + + config.after(:each) do + if Time.now - last_gc_run > 4 + GC.enable + GC.start + last_gc_run = Time.now + end + end + + # == Fixtures + # + # You can declare fixtures for each example_group like this: + # describe "...." do + # fixtures :table_a, :table_b + # + # Alternatively, if you prefer to declare them only once, you can + # do so right here. Just uncomment the next line and replace the fixture + # names with your fixtures. + # + # config.global_fixtures = :table_a, :table_b + # + # If you declare global fixtures, be aware that they will be declared + # for all of your examples, even those that don't use them. + # + # You can also declare which fixtures to use (for example fixtures for test/fixtures): + # + # config.fixture_path = Rails.root + '/spec/fixtures/' + # + # == Mock Framework + # + # RSpec uses its own mocking framework by default. If you prefer to + # use mocha, flexmock or RR, uncomment the appropriate line: + # + # config.mock_with :mocha + # config.mock_with :flexmock + # config.mock_with :rr + # + # == Notes + # + # For more information take a look at Spec::Runner::Configuration and Spec::Runner +end + +# XXX No idea what namespace/class/module to put this in + +def basic_auth_login(request, username = nil, password = nil) + username = Configuration::admin_username if username.nil? + password = Configuration::admin_password if password.nil? + request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("#{username}:#{password}") +end + +# to_ary differs in Ruby 1.8 and 1.9 +# @see http://yehudakatz.com/2010/01/02/the-craziest-fing-bug-ive-ever-seen/ +def safe_mock_model(model, args = {}) + mock = mock_model(model, args) + mock.should_receive(:to_ary).any_number_of_times + mock +end + +def load_test_categories + PublicBodyCategories.add(:en, [ + "Local and regional", + [ "local_council", "Local councils", "a local council" ], + "Miscellaneous", + [ "other", "Miscellaneous", "miscellaneous" ],]) +end + + +# Monkeypatch applicationcontroller because the `render_to_string` +# method in the original breaks all the rspec test assertions such as +# `should render_template('foo')`. Same problem as +# http://stackoverflow.com/questions/8174415/is-it-possible-to-assert-template-or-render-template-against-the-same-partial-wi +# - a bug in either Rails or Rspec I don't have the time to fix :( + +class ApplicationController < ActionController::Base + def set_popup_banner + @popup_banner = nil + end +end diff --git a/spec/support/email_helpers.rb b/spec/support/email_helpers.rb new file mode 100644 index 000000000..7e98c39f6 --- /dev/null +++ b/spec/support/email_helpers.rb @@ -0,0 +1,23 @@ +def load_raw_emails_data + raw_emails_yml = File.join(RSpec.configuration.fixture_path, "raw_emails.yml") + for raw_email_id in YAML::load_file(raw_emails_yml).map{|k,v| v["id"]} do + raw_email = RawEmail.find(raw_email_id) + raw_email.data = load_file_fixture("raw_emails/%d.email" % [raw_email_id]) + end +end + +def receive_incoming_mail(email_name, email_to, email_from = 'geraldinequango@localhost') + email_name = file_fixture_name(email_name) + content = File.read(email_name) + content.gsub!('EMAIL_TO', email_to) + content.gsub!('EMAIL_FROM', email_from) + RequestMailer.receive(content) +end + +def get_fixture_mail(filename) + MailHandler.mail_from_raw_email(load_file_fixture(filename)) +end + +def parse_all_incoming_messages + IncomingMessage.find(:all).each{ |x| x.parse_raw_email! } +end diff --git a/spec/support/load_file_fixtures.rb b/spec/support/load_file_fixtures.rb new file mode 100644 index 000000000..08079f654 --- /dev/null +++ b/spec/support/load_file_fixtures.rb @@ -0,0 +1,14 @@ +def file_fixture_name(file_name) + return File.join(RSpec.configuration.fixture_path, "files", file_name) +end + +def load_file_fixture(file_name, as_binary=false) + file_name = file_fixture_name(file_name) + content = File.open(file_name, 'r') do |file| + if as_binary + file.set_encoding(Encoding::BINARY) if file.respond_to?(:set_encoding) + end + file.read + end + return content +end diff --git a/spec/support/validate_html.rb b/spec/support/validate_html.rb new file mode 100644 index 000000000..56f384537 --- /dev/null +++ b/spec/support/validate_html.rb @@ -0,0 +1,65 @@ +# Validate an entire HTML page +def validate_html(html) + $tempfilecount = $tempfilecount + 1 + tempfilename = File.join(Dir::tmpdir, "railshtmlvalidate."+$$.to_s+"."+$tempfilecount.to_s+".html") + File.open(tempfilename, "w+") do |f| + f.puts html + end + if not system($html_validation_script, *($html_validation_script_options +[tempfilename])) + raise "HTML validation error in " + tempfilename + " HTTP status: " + @response.response_code.to_s + end + File.unlink(tempfilename) + return true +end + +# Validate HTML fragment by wrapping it as the <body> of a page +def validate_as_body(html) + validate_html('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' + + "<html><head><title>Test</title></head><body>#{html}</body></html>") +end + +# Monkeypatch! Validate HTML in tests. +$html_validation_script_found = false +Configuration::utility_search_path.each do |d| + $html_validation_script = File.join(d, "validate") + $html_validation_script_options = ["--charset=utf-8"] + if File.file? $html_validation_script and File.executable? $html_validation_script + $html_validation_script_found = true + break + end +end +if $tempfilecount.nil? + $tempfilecount = 0 + if $html_validation_script_found + module ActionController + class TestCase + module Behavior + # Hook into the process function, so can automatically get HTML after each request + alias :original_process :process + def is_fragment + # XXX there must be a better way of doing this! + return @request.path_parameters["action"] == "search_typeahead" + end + def process(action, parameters = nil, session = nil, flash = nil, http_method = 'GET') + self.original_process(action, parameters, session, flash, http_method) + # don't validate auto-generated HTML + return if @request.query_parameters["action"] == "get_attachment_as_html" + # XXX Is there a better way to check this than calling a private method? + return if @response.body.strip.empty? + # And then if HTML, not a redirect (302, 301) + if @response.content_type == "text/html" && ! [301,302,401].include?(@response.response_code) + if !is_fragment + validate_html(@response.body) + else + # it's a partial + validate_as_body(@response.body) + end + end + end + end + end + end + else + puts "WARNING: HTML validation script " + $html_validation_script + " not found" + end +end diff --git a/spec/support/xapian_index.rb b/spec/support/xapian_index.rb new file mode 100644 index 000000000..344c28ebb --- /dev/null +++ b/spec/support/xapian_index.rb @@ -0,0 +1,42 @@ +# Rebuild the current xapian index +def rebuild_xapian_index(terms = true, values = true, texts = true, dropfirst = true) + if dropfirst + begin + ActsAsXapian.readable_init + FileUtils.rm_r(ActsAsXapian.db_path) + rescue RuntimeError + end + ActsAsXapian.writable_init + ActsAsXapian.writable_db.close + end + parse_all_incoming_messages + # safe_rebuild=true, which involves forking to avoid memory leaks, doesn't work well with rspec. + # unsafe is significantly faster, and we can afford possible memory leaks while testing. + models = [PublicBody, User, InfoRequestEvent] + ActsAsXapian.rebuild_index(models, verbose=false, terms, values, texts, safe_rebuild=false) +end + +def update_xapian_index + ActsAsXapian.update_index(flush_to_disk=false, verbose=false) +end + +# Copy the xapian index created in create_fixtures_xapian_index to a temporary +# copy at the same level and point xapian at the copy +def get_fixtures_xapian_index() + # Create a base index for the fixtures if not already created + $existing_xapian_db ||= create_fixtures_xapian_index + # Store whatever the xapian db path is originally + $original_xapian_path ||= ActsAsXapian.db_path + path_array = $original_xapian_path.split(File::Separator) + path_array.pop + temp_path = File.join(path_array, 'test.temp') + FileUtils.remove_entry_secure(temp_path, force=true) + FileUtils.cp_r($original_xapian_path, temp_path) + ActsAsXapian.db_path = temp_path +end + +# Create a clean xapian index based on the fixture files and the raw_email data. +def create_fixtures_xapian_index + load_raw_emails_data + rebuild_xapian_index +end diff --git a/spec/views/public_body/show.rhtml_spec.rb b/spec/views/public_body/show.rhtml_spec.rb index b68b3f43b..1a972a661 100644 --- a/spec/views/public_body/show.rhtml_spec.rb +++ b/spec/views/public_body/show.rhtml_spec.rb @@ -1,6 +1,6 @@ require File.expand_path(File.join('..', '..', '..', 'spec_helper'), __FILE__) -describe "when viewing a body" do +describe "public_body/show" do before do @pb = mock_model(PublicBody, :name => 'Test Quango', @@ -17,64 +17,62 @@ describe "when viewing a body" do @pb.stub!(:is_requestable?).and_return(true) @pb.stub!(:has_notes?).and_return(false) @pb.stub!(:has_tag?).and_return(false) - @xap = mock_model(ActsAsXapian::Search, :matches_estimated => 2) + @xap = mock(ActsAsXapian::Search, :matches_estimated => 2) @xap.stub!(:results).and_return([ { :model => mock_event }, { :model => mock_event } ]) - assigns[:public_body] = @pb - assigns[:track_thing] = mock_model(TrackThing, - :track_type => 'public_body_updates', :public_body => @pb, :params => {}) - assigns[:xapian_requests] = @xap - assigns[:page] = 1 - assigns[:per_page] = 10 - # work round a bug in ActionController::TestRequest; allows request.query_string to work in the template - request.env["REQUEST_URI"] = "" + assign(:public_body, @pb) + assign(:track_thing, mock_model(TrackThing, + :track_type => 'public_body_updates', :public_body => @pb, :params => {})) + assign(:xapian_requests, @xap) + assign(:page, 1) + assign(:per_page, 10) end it "should be successful" do - render "public_body/show" - response.should be_success + render + controller.response.should be_success end it "should be valid HTML" do - render "public_body/show" + render validate_as_body response.body end it "should show the body's name" do - render "public_body/show" - response.should have_tag("h1", "Test Quango") + render + response.should have_selector('h1', :content => "Test Quango") end it "should tell total number of requests" do - render "public_body/show" - response.should include_text("4 Freedom of Information requests") + render + response.should match "4 Freedom of Information requests" end it "should cope with no results" do @pb.stub!(:info_requests).and_return([]) - render "public_body/show" - response.should have_tag("p", /Nobody has made any Freedom of Information requests/m) + render + response.should have_selector('p', :content => "Nobody has made any Freedom of Information requests") end it "should cope with Xapian being down" do - assigns[:xapian_requests] = nil - render "public_body/show" - response.should have_tag("p", /The search index is currently offline/m) + assign(:xapian_requests, nil) + render + response.should match "The search index is currently offline" end it "should link to Charity Commission site if we have numbers to do so" do @pb.stub!(:has_tag?).and_return(true) @pb.stub!(:get_tag_values).and_return(['98765', '12345']) - render "public_body/show" - response.should have_tag("div#header_right") do - with_tag("a[href*=?]", /charity-commission.gov.uk.*RegisteredCharityNumber=98765$/) + render + response.should have_selector("div#header_right") do + have_selector "a", :href => /charity-commission.gov.uk.*RegisteredCharityNumber=98765$/ end - response.should have_tag("div#header_right") do - with_tag("a[href*=?]", /charity-commission.gov.uk.*RegisteredCharityNumber=12345$/) + response.should have_selector("div#header_right") do + have_selector "a", :href => /www.charity-commission.gov.uk.*RegisteredCharityNumber=12345$/ end end @@ -82,17 +80,17 @@ describe "when viewing a body" do @pb.stub!(:has_tag?).and_return(true) @pb.stub!(:get_tag_values).and_return(['SC1234']) - render "public_body/show" - response.should have_tag("div#header_right") do - with_tag("a[href*=?]", /www.oscr.org.uk.*id=SC1234$/) + render + response.should have_selector("div#header_right") do + have_selector "a", :href => /www.oscr.org.uk.*id=SC1234$/ end end it "should not link to Charity Commission site if we don't have number" do - render "public_body/show" - response.should have_tag("div#header_right") do - without_tag("a[href*=?]", /charity-commission.gov.uk/) + render + response.should have_selector("div#header_right") do + have_selector "a", :href => /charity-commission.gov.uk/ end end diff --git a/spec/views/request/_after_actions.rhtml_spec.rb b/spec/views/request/_after_actions.rhtml_spec.rb index 548990c9f..ae398f4ce 100644 --- a/spec/views/request/_after_actions.rhtml_spec.rb +++ b/spec/views/request/_after_actions.rhtml_spec.rb @@ -15,51 +15,27 @@ describe 'when displaying actions that can be taken with regard to a request' do :comments_allowed? => true, :url_title => 'test_request', :all_can_view? => true) - assigns[:info_request] = @mock_request - end - - def do_render - render :partial => 'request/after_actions' - end - - def expect_owner_div - do_render - response.should have_tag('div#owner_actions'){ yield } - end - - def expect_anyone_div - do_render - response.should have_tag('div#anyone_actions'){ yield } - end - - def expect_owner_link(text) - expect_owner_div{ with_tag('a', :text => text) } - end - - def expect_no_owner_link(text) - expect_owner_div{ without_tag('a', :text => text) } - end - - def expect_anyone_link(text) - expect_anyone_div{ with_tag('a', :text => text) } - end - - def expect_no_anyone_link(text) - expect_anyone_div{ without_tag('a', :text => text) } + assign :info_request, @mock_request end describe 'if the request is old and unclassified' do before do - assigns[:old_unclassified] = true + assign :old_unclassified, true end it 'should not display a link for the request owner to update the status of the request' do - expect_no_owner_link('Update the status of this request') + render :partial => 'request/after_actions' + response.should have_selector('div#owner_actions') do |div| + div.should_not have_selector('a', :content => 'Update the status of this request') + end end it 'should display a link for anyone to update the status of the request' do - expect_anyone_link('Update the status of this request') + render :partial => 'request/after_actions' + response.should have_selector('div#anyone_actions') do |div| + div.should have_selector('a', :content => 'Update the status of this request') + end end end @@ -67,27 +43,39 @@ describe 'when displaying actions that can be taken with regard to a request' do describe 'if the request is not old and unclassified' do before do - assigns[:old_unclassified] = false + assign :old_unclassified, false end it 'should display a link for the request owner to update the status of the request' do - expect_owner_link('Update the status of this request') + render :partial => 'request/after_actions' + response.should have_selector('div#owner_actions') do |div| + div.should have_selector('a', :content => 'Update the status of this request') + end end it 'should not display a link for anyone to update the status of the request' do - expect_no_anyone_link('Update the status of this request') + render :partial => 'request/after_actions' + response.should have_selector('div#anyone_actions') do |div| + div.should_not have_selector('a', :content => 'Update the status of this request') + end end end it 'should display a link for the request owner to request a review' do - expect_owner_link('Request an internal review') + render :partial => 'request/after_actions' + response.should have_selector('div#owner_actions') do |div| + div.should have_selector('a', :content => 'Request an internal review') + end end describe 'if the request is viewable by all' do it 'should display the link to download the entire request' do - expect_anyone_link('Download a zip file of all correspondence') + render :partial => 'request/after_actions' + response.should have_selector('div#anyone_actions') do |div| + div.should have_selector('a', :content => 'Download a zip file of all correspondence') + end end end @@ -95,7 +83,10 @@ describe 'when displaying actions that can be taken with regard to a request' do it 'should not display the link to download the entire request' do @mock_request.stub!(:all_can_view?).and_return(false) - expect_no_anyone_link('Download a zip file of all correspondence') + render :partial => 'request/after_actions' + response.should have_selector('div#anyone_actions') do |div| + div.should_not have_selector('a', :content => 'Download a zip file of all correspondence') + end end end diff --git a/spec/views/request/_describe_state.rhtml_spec.rb b/spec/views/request/_describe_state.rhtml_spec.rb index 18778d5d2..88dea53c5 100644 --- a/spec/views/request/_describe_state.rhtml_spec.rb +++ b/spec/views/request/_describe_state.rhtml_spec.rb @@ -4,12 +4,12 @@ describe 'when showing the form for describing the state of a request' do def expect_radio_button(value) do_render - response.should have_tag("input[type=radio][value=#{value}]") + response.should have_selector('input', :type => 'radio', :value => value) end def expect_no_radio_button(value) do_render - response.should_not have_tag("input[type=radio][value=#{value}]") + response.should_not have_selector('input', :type => 'radio', :value => value) end def do_render @@ -24,25 +24,25 @@ describe 'when showing the form for describing the state of a request' do :user_name => @mock_user.name, :is_external? => false ) - assigns[:info_request] = @mock_request + assign :info_request, @mock_request end describe 'if the user is a regular user (not the request owner)' do before do - assigns[:is_owning_user] = false + assign :is_owning_user, false end describe 'if the request is not old and unclassified' do it 'should not show the form' do do_render - response.should_not have_tag('h2', :text => 'What best describes the status of this request now?') + response.should_not have_selector('h2', :content => 'What best describes the status of this request now?') end it 'should give a link to login' do do_render - response.should have_tag('a', :text => 'sign in') + response.should have_selector('a', :content => 'sign in') end end @@ -50,22 +50,22 @@ describe 'when showing the form for describing the state of a request' do describe 'if the request is old and unclassified' do before do - assigns[:old_unclassified] = true + assign :old_unclassified, true end it 'should not show the form' do do_render - response.should_not have_tag('h2', :text => 'What best describes the status of this request now?') + response.should_not have_selector('h2', :content => 'What best describes the status of this request now?') end it 'should show the form for someone else to classify the request' do do_render - response.should have_tag('h2', :text => /We need your help/) + response.should have_selector('h2', :content => 'We need your help') end it 'should not give a link to login' do do_render - response.should_not have_tag('a', :text => 'sign in') + response.should_not have_selector('a', :content => 'sign in') end end @@ -74,7 +74,7 @@ describe 'when showing the form for describing the state of a request' do describe 'if showing the form to the user owning the request' do before do - assigns[:is_owning_user] = true + assign :is_owning_user, true end describe 'when the request is not in internal review' do @@ -100,7 +100,7 @@ describe 'when showing the form for describing the state of a request' do describe 'when the user has asked to update the status of the request' do before do - assigns[:update_status] = true + assign :update_status, true end it 'should show a radio button to set the status to "internal_review"' do @@ -129,7 +129,7 @@ describe 'when showing the form for describing the state of a request' do it 'should show the text "The review has finished and overall:"' do do_render - response.should have_tag('p', :text => 'The review has finished and overall:') + response.should have_selector('p', :content => 'The review has finished and overall:') end end @@ -170,4 +170,4 @@ describe 'when showing the form for describing the state of a request' do end end -end
\ No newline at end of file +end diff --git a/spec/views/request/list.rhtml_spec.rb b/spec/views/request/list.rhtml_spec.rb index 137bc359d..521d946bc 100644 --- a/spec/views/request/list.rhtml_spec.rb +++ b/spec/views/request/list.rhtml_spec.rb @@ -1,12 +1,10 @@ require File.expand_path(File.join('..', '..', '..', 'spec_helper'), __FILE__) -describe "when listing recent requests" do +describe "request/list" do before do - assigns[:page] = 1 - assigns[:per_page] = 10 - # work round a bug in ActionController::TestRequest; allows request.query_string to work in the template - request.env["REQUEST_URI"] = "" + assign :page, 1 + assign :per_page, 10 end def make_mock_event @@ -30,21 +28,21 @@ describe "when listing recent requests" do end it "should be successful" do - assigns[:list_results] = [ make_mock_event, make_mock_event ] - assigns[:matches_estimated] = 2 - assigns[:show_no_more_than] = 100 - render "request/list" - response.should have_tag("div.request_listing") - response.should_not have_tag("p", /No requests of this sort yet/m) + assign :list_results, [ make_mock_event, make_mock_event ] + assign :matches_estimated, 2 + assign :show_no_more_than, 100 + render + response.should have_selector("div.request_listing") + response.should_not have_selector("p", :content => "No requests of this sort yet") end it "should cope with no results" do - assigns[:list_results] = [ ] - assigns[:matches_estimated] = 0 - assigns[:show_no_more_than] = 0 - render "request/list" - response.should have_tag("p", /No requests of this sort yet/m) - response.should_not have_tag("div.request_listing") + assign :list_results, [ ] + assign :matches_estimated, 0 + assign :show_no_more_than, 0 + render + response.should have_selector("p", :content => "No requests of this sort yet") + response.should_not have_selector("div.request_listing") end end diff --git a/spec/views/request/show.rhtml_spec.rb b/spec/views/request/show.rhtml_spec.rb index 4429e9e58..cc5226847 100644 --- a/spec/views/request/show.rhtml_spec.rb +++ b/spec/views/request/show.rhtml_spec.rb @@ -23,32 +23,23 @@ describe 'when viewing an information request' do end def request_page - assigns[:info_request] = @mock_request - assigns[:info_request_events] = [] - assigns[:status] = @mock_request.calculate_status - template.stub!(:render_partial) - render 'request/show' - end - - it 'should show the sidebar' do - template.should_receive(:render_partial).with(:partial => 'sidebar', :locals => {}) - request_page - end - - it 'should show the actions people can take' do - template.should_receive(:render_partial).with(:partial => 'after_actions', :locals => {}) - request_page + assign :info_request, @mock_request + assign :info_request_events, [] + assign :status, @mock_request.calculate_status + # This is so icky! + view.stub!(:_render_partial) + render :template => 'request/show' end describe 'when a status update has been requested' do before do - assigns[:update_status] = true + assign :update_status, true end it 'should show the first form for describing the state of the request' do request_page - response.should have_tag("div.describe_state_form#describe_state_form_1") + response.should have_selector("div.describe_state_form#describe_state_form_1") end end @@ -61,12 +52,12 @@ describe 'when viewing an information request' do it 'should show the first form for describing the state of the request' do request_page - response.should have_tag("div.describe_state_form#describe_state_form_1") + response.should have_selector("div.describe_state_form#describe_state_form_1") end it 'should show the second form for describing the state of the request' do request_page - response.should have_tag("div.describe_state_form#describe_state_form_2") + response.should have_selector("div.describe_state_form#describe_state_form_2") end end @@ -74,7 +65,7 @@ describe 'when viewing an information request' do describe 'when the user is the request owner' do before do - assigns[:is_owning_user] = true + assign :is_owning_user, true end describe 'when the request status is "waiting clarification"' do @@ -88,18 +79,13 @@ describe 'when viewing an information request' do before do @mock_response = mock_model(IncomingMessage) @mock_request.stub!(:get_last_response).and_return(@mock_response) - @old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new - end - after do - ActionController::Routing::Routes.filters = @old_filters end it 'should show a link to follow up the last response with clarification' do request_page - expected_url = "http://test.host/request/#{@mock_request.id}/response/#{@mock_response.id}#followup" - response.should have_tag("a[href=#{expected_url}]", :text => 'send a follow up message') + expected_url = "http://test.host/en/request/#{@mock_request.id}/response/#{@mock_response.id}#followup" + response.should have_selector("a", :href => expected_url, :content => 'send a follow up message') end end @@ -108,18 +94,13 @@ describe 'when viewing an information request' do before do @mock_request.stub!(:get_last_response).and_return(nil) - @old_filters = ActionController::Routing::Routes.filters - ActionController::Routing::Routes.filters = RoutingFilter::Chain.new - end - after do - ActionController::Routing::Routes.filters = @old_filters end it 'should show a link to follow up the request without reference to a specific response' do request_page - expected_url = "http://test.host/request/#{@mock_request.id}/response#followup" - response.should have_tag("a[href=#{expected_url}]", :text => 'send a follow up message') + expected_url = "http://test.host/en/request/#{@mock_request.id}/response#followup" + response.should have_selector("a", :href => expected_url, :content => 'send a follow up message') end end end diff --git a/spec/views/request_game/play.rhtml_spec.rb b/spec/views/request_game/play.rhtml_spec.rb index 24fb6d75d..b5cf57c23 100644 --- a/spec/views/request_game/play.rhtml_spec.rb +++ b/spec/views/request_game/play.rhtml_spec.rb @@ -1,6 +1,6 @@ require File.expand_path(File.join('..', '..', '..', 'spec_helper'), __FILE__) -describe 'when viewing the request game' do +describe 'request_game/play' do before do @mock_body = mock_model(PublicBody, :name => 'test body', @@ -22,15 +22,15 @@ describe 'when viewing the request game' do :initial_request_text => 'hi there', :display_status => 'Awaiting categorisation', :created_at => Time.now) - assigns[:league_table_28_days] = [] - assigns[:league_table_all_time] = [] - assigns[:requests] = [@mock_request] - assigns[:play_urls] = true + assign :league_table_28_days, [] + assign :league_table_all_time, [] + assign :requests, [@mock_request] + assign :play_urls, true end it 'should show the correct url for a request' do - render "request_game/play" - response.should include_text("/categorise/request/a_test_request") + render + response.should include("/categorise/request/a_test_request") end |