<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: testing code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sun, 27 Jul 2008 09:13:33 GMT</pubDate>
    <description>DZone Snippets: testing code</description>
    <item>
      <title>load all fixtures</title>
      <link>http://snippets.dzone.com/posts/show/5007</link>
      <description>In some test cases I need all my fixtures to be loaded.  To make this easier, add the following to test/test_helper.rb:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class Test::Unit::TestCase&lt;br /&gt;  def self.all_fixtures&lt;br /&gt;    Dir[File.dirname(__FILE__) + "/fixtures/*.yml"].each do |f|&lt;br /&gt;      fixtures File.basename(f, '.yml')&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  ..&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;and in your tests use it as follows:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class FooTest &lt; Test::Unit::TestCase&lt;br /&gt;  all_fixtures&lt;br /&gt;&lt;br /&gt;  ..&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Happy testing!</description>
      <pubDate>Fri, 18 Jan 2008 19:01:16 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5007</guid>
      <author>remvee (Remco van 't Veer)</author>
    </item>
    <item>
      <title>Make Time "Stand Still" in Ruby</title>
      <link>http://snippets.dzone.com/posts/show/4776</link>
      <description>When writing tests, it's sometimes difficult to test results of methods that use current time. Two calls to Time.now can give different results and cause test failures. Here is some code that lets you execute a block during which Time.now will return a consistent value:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class Time&lt;br /&gt;&lt;br /&gt;  # this code adds a Time.freeze method to make time "stand still"&lt;br /&gt;  # during execution of a block. This can be helpful during testing of&lt;br /&gt;  # methods that depend on Time.new or Time.now&lt;br /&gt;  #&lt;br /&gt;  # Example:&lt;br /&gt;  #&lt;br /&gt;  #   Time.freeze do&lt;br /&gt;  #      puts Time.new.to_f&lt;br /&gt;  #      # ... do stuff; real time passes&lt;br /&gt;  #      puts Time.new.to_f     # outputs same time as above&lt;br /&gt;  #   end&lt;br /&gt;  #   # ... time returns to normal&lt;br /&gt;  #&lt;br /&gt;  # An optional Time object may be passed to freeze to a specific time:&lt;br /&gt;  #&lt;br /&gt;  #   Time.freeze(Time.at(2007, 11, 15)) do&lt;br /&gt;  #      # ...&lt;br /&gt;  #   end&lt;br /&gt;  #&lt;br /&gt;  # While inside the block, Time.frozen? will return true&lt;br /&gt;&lt;br /&gt;  class &lt;&lt; self&lt;br /&gt;&lt;br /&gt;    def now&lt;br /&gt;      @time || orig_new&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;    alias_method :orig_freeze, :freeze&lt;br /&gt;    alias_method :orig_new, :new&lt;br /&gt;    alias_method :new, :now&lt;br /&gt;&lt;br /&gt;    # makes time "stand still" during execution of a block. if no time is&lt;br /&gt;    # supplied, the current time is used. While in the block, Time.new and&lt;br /&gt;    # Time.now will always return the "frozen" value.&lt;br /&gt;    def freeze(time = nil)&lt;br /&gt;      raise "A block is required" unless block_given?&lt;br /&gt;      begin&lt;br /&gt;        prev = @time&lt;br /&gt;        @time = time || now&lt;br /&gt;        yield&lt;br /&gt;      ensure&lt;br /&gt;        @time = prev&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;    def frozen?&lt;br /&gt;      !@time.nil?&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 15 Nov 2007 21:36:47 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4776</guid>
      <author>bshow (Bob Showalter)</author>
    </item>
    <item>
      <title>rcov rake task for rails project</title>
      <link>http://snippets.dzone.com/posts/show/4525</link>
      <description>This task will create a folder (doc/coverage) then run all of your tests and produce HTML with code coverage information in that folder. If you are on a mac it will even open the index.html file up for you automatically&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# this requires the RCOV gem to be installed on your system&lt;br /&gt;namespace :test do&lt;br /&gt;  desc "Generate code coverage with rcov"&lt;br /&gt;  task :coverage do&lt;br /&gt;    rm_f "doc/coverage/coverage.data"&lt;br /&gt;    rm_f "doc/coverage"&lt;br /&gt;    mkdir "doc/coverage"&lt;br /&gt;    rcov = %(rcov --rails --aggregate doc/coverage/coverage.data --text-summary -Ilib --html -o doc/coverage test/**/*_test.rb)&lt;br /&gt;    system rcov&lt;br /&gt;    system "open doc/coverage/index.html" if PLATFORM['darwin']&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 11 Sep 2007 16:13:45 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4525</guid>
      <author>akbloom (Andrew Bloom)</author>
    </item>
    <item>
      <title>Helper for testing default routes generated by a resource in Ruby on Rails</title>
      <link>http://snippets.dzone.com/posts/show/4517</link>
      <description>These methods test that the routes for resources defined in routes.rb are working as expected. Call them from your functional (controller) tests.&lt;br /&gt;&lt;br /&gt;Add the following 3 methods to test/test_helper.rb (updated for Rails 1.2.5 which no longer uses semicolons as a separator for the edit action):&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# Test for routes generated by map.resource (singular).&lt;br /&gt;def assert_routing_for_resource(controller, skip=[], nesting=[])&lt;br /&gt;  routes = [&lt;br /&gt;    ["new",'/new',{},:get], ["create",'',{},:post],&lt;br /&gt;    ["show",'',{},:get], ["edit",'/edit',{},:get],&lt;br /&gt;    ["update",'',{},:put], ["destroy",'',{},:delete]&lt;br /&gt;    ]&lt;br /&gt;  check_resource_routing(controller, routes, skip, nesting)&lt;br /&gt;end&lt;br /&gt;# Test for routes generated by map.resources (plural).&lt;br /&gt;def assert_routing_for_resources(controller, skip=[], nesting=[])&lt;br /&gt;  routes = [&lt;br /&gt;    ["index",'',{},:get], ["new",'/new',{},:get], ["create",'',{},:post],&lt;br /&gt;    ["show",'/1',{:id=&gt;'1'},:get], ["edit",'/1/edit',{:id=&gt;'1'},:get],&lt;br /&gt;    ["update",'/1',{:id=&gt;'1'},:put], ["destroy",'/1',{:id=&gt;'1'},:delete]&lt;br /&gt;    ]&lt;br /&gt;  check_resource_routing(controller, routes, skip, nesting)&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# Check that the expected paths will be generated by a resource, and that&lt;br /&gt;# the expected params will be generated by paths defined by a resource.&lt;br /&gt;# routes is array of [action, url string after controller, extra params].&lt;br /&gt;def check_resource_routing(controller, routes, skip=[], nesting=[])&lt;br /&gt;  # set a prefix for nested resources&lt;br /&gt;  prefix = nesting.join('s/1/')&lt;br /&gt;  unless prefix.blank?&lt;br /&gt;    prefix += "s/1/"&lt;br /&gt;  end&lt;br /&gt;  # Add params for nested resources.&lt;br /&gt;  # For each 'nest', include a ":nest_id=&gt;'1'" param.&lt;br /&gt;  params = {}&lt;br /&gt;  nesting.each do |param|&lt;br /&gt;    params["#{param}_id".to_sym] = '1'&lt;br /&gt;  end&lt;br /&gt;  # Test each of the standard resource routes.&lt;br /&gt;  routes.each do |pair|&lt;br /&gt;    unless skip.include? pair[0]&lt;br /&gt;      assert_generates("/#{prefix}#{controller}#{pair[1]}",&lt;br /&gt;        {:controller=&gt;controller,&lt;br /&gt;        :action=&gt;pair[0]}.merge(pair[2]).merge(params), {}, {},&lt;br /&gt;        "Failed generation of resource route for action #{pair[0]} /#{prefix}#{controller}#{pair[1]}")&lt;br /&gt;      assert_recognizes(&lt;br /&gt;        {:controller=&gt;controller,&lt;br /&gt;          :action=&gt;pair[0]}.merge(pair[2]).merge(params),&lt;br /&gt;        {:path=&gt;"/#{prefix}#{controller}#{pair[1]}", :method=&gt;pair[3]},&lt;br /&gt;        {}, "Failed to recognize resource route for path #{pair[3]}:/#{prefix}#{controller}#{pair[1]}")&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;EXAMPLES&lt;br /&gt;&lt;br /&gt;You can specify actions to 'skip' (if you have a special route for that action).&lt;br /&gt;If using nested resources, set the nesting array (use singular strings).&lt;br /&gt;&lt;br /&gt;So, if you have the following in routes.rb:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;map.make_thing '/make', :controller=&gt;'things', :action=&gt;'new'&lt;br /&gt;map.resources :nests do |nest|&lt;br /&gt;  nest.resources :things&lt;br /&gt;end&lt;br /&gt;map.resource :foo&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;then you can use the following in things_controller_test.rb:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def test_resource_routing&lt;br /&gt;  assert_routing_for_resources 'things', ['new'], ['nest']&lt;br /&gt;  assert_routing_for_resource 'foo'&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 10 Sep 2007 12:46:23 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4517</guid>
      <author>grantneufeld (Grant Neufeld)</author>
    </item>
    <item>
      <title>Testing for Exception message in Rails</title>
      <link>http://snippets.dzone.com/posts/show/4320</link>
      <description>&lt;code&gt;&lt;br /&gt;e = assert_raise(RuntimeError) { my_code_that_raises }&lt;br /&gt;assert_match(/Error message here/i, e.message)..&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 18 Jul 2007 14:39:53 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4320</guid>
      <author>sikelianos (Zeke Sikelianos)</author>
    </item>
    <item>
      <title>Custom headers in Rails tests</title>
      <link>http://snippets.dzone.com/posts/show/3785</link>
      <description>From time to time you may need to set headers in your functional tests that aren't supported by the @request object.  I had to set up my request with Basic authentication.&lt;br /&gt;&lt;br /&gt;Add an extension to the TestRequest class in the test/test_helper.rb file:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class ActionController::TestRequest &lt;br /&gt;  def set_header(name, value)&lt;br /&gt;    @env[name] = value&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Then set values as required in your functional test.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def test_index&lt;br /&gt;  @request.set_header "HTTP_AUTHORIZATION", "Basic " + Base64.encode64('testuser:testpass')&lt;br /&gt;  get :index&lt;br /&gt;  assert_response :success&lt;br /&gt;  assert_template "index"&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sat, 07 Apr 2007 16:49:18 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3785</guid>
      <author>rodfrey (Rod Frey)</author>
    </item>
    <item>
      <title>In Place Testing for Ruby methods</title>
      <link>http://snippets.dzone.com/posts/show/3753</link>
      <description>This is something kinda experimental I'm working on. Testing is cool, but I hate that it's separate from my code. Perhaps that's stupidity on my part, but I wanted to see if there's a way to bring the lowest level of testing directly into the class..&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;module InPlaceTesting&lt;br /&gt;  def self.included(klass)&lt;br /&gt;    old_method_added = klass.method(:method_added)&lt;br /&gt;    new_method_added = lambda do |m|&lt;br /&gt;      @@current_method = m&lt;br /&gt;      old_method_added.call m&lt;br /&gt;    end&lt;br /&gt;    &lt;br /&gt;    # Next line inspired by http://utils.ning.com/ruby/dbc.rb by Brian McCallister and Martin Traverso&lt;br /&gt;    (class &lt;&lt; klass; self; end).send :define_method, :method_added, new_method_added&lt;br /&gt;    &lt;br /&gt;    class &lt;&lt; klass&lt;br /&gt;      def given(*args)&lt;br /&gt;        self.new.send @@current_method, *args&lt;br /&gt;      end&lt;br /&gt;      def method_should(message, params)&lt;br /&gt;        unless params[:return] == params[:when]&lt;br /&gt;          puts "\"#{@@current_method}\" fails to #{message} (returns #{params[:when]} instead of #{params[:return]})"&lt;br /&gt;        end&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;    &lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class DumbClass&lt;br /&gt;  include InPlaceTesting&lt;br /&gt;&lt;br /&gt;  def add(x,y) &lt;br /&gt;    x + y&lt;br /&gt;  end&lt;br /&gt;  method_should "add 5 and 4", :return =&gt; 9, :when =&gt; given(5, 4)&lt;br /&gt;&lt;br /&gt;  def subtract(x,y) &lt;br /&gt;    x - y&lt;br /&gt;  end &lt;br /&gt;  method_should "subtract 5 from 14", :return =&gt; 9, :when =&gt; given(14,5)&lt;br /&gt;  &lt;br /&gt;  def increment(x)&lt;br /&gt;    x + 1&lt;br /&gt;  end&lt;br /&gt;  method_should "increment 12", :return =&gt; 13, :when =&gt; given(12)&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 02 Apr 2007 08:13:22 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3753</guid>
      <author>peter (Peter Cooperx)</author>
    </item>
    <item>
      <title>test</title>
      <link>http://snippets.dzone.com/posts/show/3103</link>
      <description>// description of your code here&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;?&lt;br /&gt;	if (in_array($r["type"], Array(1, print str_replace("; ;","",(get_part_of_text($desc, 300)));&lt;br /&gt;	else { $sql-&gt;query("SELECT of.phone FROM offers o, offices of&lt;br /&gt;			WHERE o.office_id=of.id AND o.id=".$r["id"]);&lt;br /&gt;		list($office_phone) = $sql-&gt;getrow(&lt;br /&gt;print (str_replace("; ;","",(get_part_of_text($desc,300))))."&lt;br/&gt;&lt;b&gt;Contacts&lt;/b&gt;:".$office_phone;&lt;br /&gt;	}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 07 Dec 2006 17:47:00 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3103</guid>
      <author>bugmenot (BugMeNot)</author>
    </item>
    <item>
      <title>#post method in tests with a different controller</title>
      <link>http://snippets.dzone.com/posts/show/2880</link>
      <description>I wanted a #login method in test_helper that would allow me to easily login from any of my functional tests.  However, the #post method won't allow you to set a different controller than the one in the @controller instance variable that's defined in your test's #setup.  Well, by looking at how the &lt;a href="http://api.rubyonrails.org/classes/ActionController/TestProcess.html#M000046"&gt;#process method&lt;/a&gt; works, you can see that it just grabs the controller from @controller.  Redefine that, and you're good to go:&lt;br /&gt;&lt;code&gt;old_controller = @controller&lt;br /&gt;@controller = LoginController.new&lt;br /&gt;post(&lt;br /&gt;  :attempt_login,&lt;br /&gt;  {:user =&gt; {:name =&gt; 'joe', :password =&gt; 'password'}}&lt;br /&gt;)&lt;br /&gt;@controller = old_controller&lt;/code&gt;&lt;br /&gt;If you have several login methods, such as a #login_admin and #login_regular, you could make a wrapper to reduce duplication:&lt;br /&gt;&lt;code&gt;def wrap_with_controller( new_controller = LoginController )&lt;br /&gt;  old_controller = @controller&lt;br /&gt;  @controller = new_controller.new&lt;br /&gt;  yield&lt;br /&gt;  @controller = old_controller&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def login_admin&lt;br /&gt;  wrap_with_controller do&lt;br /&gt;    post(&lt;br /&gt;      :attempt_login,&lt;br /&gt;      {:user =&gt; {:name =&gt; 'root', :password =&gt; 'password'}}&lt;br /&gt;    )&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def login_regular&lt;br /&gt;  wrap_with_controller do&lt;br /&gt;    post(&lt;br /&gt;      :attempt_login,&lt;br /&gt;      {:user =&gt; {:name =&gt; 'joe', :password =&gt; 'password'}}&lt;br /&gt;    )&lt;br /&gt;  end&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;</description>
      <pubDate>Tue, 24 Oct 2006 18:54:12 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/2880</guid>
      <author>moneypenny ()</author>
    </item>
    <item>
      <title>Create YAML test fixtures from database in Rails</title>
      <link>http://snippets.dzone.com/posts/show/2525</link>
      <description>As found at &lt;a href="http://media.pragprog.com/titles/fr_rr/code/CreateFixturesFromLiveData/lib/tasks/extract_fixtures.rake"&gt;http://media.pragprog.com/titles/fr_rr/code/CreateFixturesFromLiveData/lib/tasks/extract_fixtures.rake&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;desc 'Create YAML test fixtures from data in an existing database.  &lt;br /&gt;Defaults to development database.  Set RAILS_ENV to override.'&lt;br /&gt;&lt;br /&gt;task :extract_fixtures =&gt; :environment do&lt;br /&gt;  sql  = "SELECT * FROM %s"&lt;br /&gt;  skip_tables = ["schema_info"]&lt;br /&gt;  ActiveRecord::Base.establish_connection&lt;br /&gt;  (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|&lt;br /&gt;    i = "000"&lt;br /&gt;    File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|&lt;br /&gt;      data = ActiveRecord::Base.connection.select_all(sql % table_name)&lt;br /&gt;      file.write data.inject({}) { |hash, record|&lt;br /&gt;        hash["#{table_name}_#{i.succ!}"] = record&lt;br /&gt;        hash&lt;br /&gt;      }.to_yaml&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 04 Sep 2006 01:48:31 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/2525</guid>
      <author>jswizard (JavaScript Wizard)</author>
    </item>
  </channel>
</rss>
