Module: Web::Testing

Defined in:
lib/web/testing.rb

Overview

Purpose

The testing module facilitates the testing of Web applications without the overhead of a web server to run.

Given these files:

script.rb
test.rb

where script.rb is:

#!/usr/bin/ruby
require 'web'

Web::process { 
 Web.write "param is #{Web["param"]}"
}

and test.rb is:

require 'web'
require 'test/unit'

class MyAppTest < Test::Unit::TestCase
   include Web::Testing

   def test_prints_content
       do_request "script.rb", "param" => "THIS!"
       assert_content "param is THIS!"
   end
end

Do this to run tests:

ruby test.rb

If you have a more complicated app, where the tests live in a different place than your scripts, you can use:

Web::set_docroot( path )

To tell narf where to find your cgi scripts.

Testing with Templates

Using Narflates you can test functionality without having to do lengthly string comparisons. For example, create the following file in 'mytemplate.html'

<html>
  <body>
    {$myvar}
  </body>
</html>

Create a 'script.rb' as follows:

#!/usr/bin/narf
require 'web'

Web::process{
  Web.print_template "mytemplate.html", { "myvar" => "Hello World" }
}

Now, we can check that the right values got displayed without needing to check that the template is correct as a side effect. Save this into 'test.rb' and run it:

require 'web'

class MyAppTest < Test::Unit::TestCase
    include Web::Testing          # adds the modules

    def test_prints_content
        do_request "script.rb"
        assert_vars_includes "myvar" => "Hello World"
      end
end

Testing Forms

The following example demonstrates testing a simple HTML form. Creating mytemplate.html as:

<html>
  <body>
    <form name="myform">
      <input type="text" name="foo">
      <input type="submit" name="submit" value="Submit">
  </body>
</html>

To print this form and handle a submit save this as 'script.rb':

#!/usr/bin/narf

require 'web'

Web::process {
  if Web["submit"]   # check to see whether a form was
      Web.puts "Form Submitted with value '#{Web["foo"]}'"  
  else
      Web.print_template "mytemplate.html"
  end
}

Use this 'test.rb' to test it:

class MyAppTest < Test::Unit::TestCase
    include Web::Testing          # adds the modules

    def test_prints_content
          do_request "script.rb"
        do_submit "myform", "foo" => "bar"
        assert_content "Form Submitted with value '#{Web["foo"]}'"
      end
end

Test and