Testing your Rails Plugins April 24th, 2008
A great feature in Ruby is the integrated testing. Ruby on Rails also implements and extends the Ruby testing framework, and if you’re not testing your Ruby code you should start doing it now!
Normally, when I write tests for a class, I mock out everything not related directly to the class (I do this with mocha). For example, when writing tests for the Mollom gem, I mocked out the whole XMLRPC API, because I can’t rely on them to give me all test cases.
# from http://github.com/DefV/ruby-mollom/tree/master/test/mollom_test.rb def test_server_list xml_rpc = mock xml_rpc.expects(:call). with('mollom.getServerList', is_a(Hash)). returns(['http://172.16.0.1', 'http://172.16.0.2', 'https://172.16.0.2']) XMLRPC::Client.stubs(:new).with('xmlrpc.mollom.com', '/1.0').returns(xml_rpc) assert_equal [ {:ip => '172.16.0.1', :proto => 'http'}, {:ip => '172.16.0.2', :proto => 'http'}, {:ip => '172.16.0.2', :proto => 'https'} ], @mollom.server_list end
This way, I’m only testing the behaviour of that specific class, so if something fails somewhere, I can pinpoint the problem, while being sure it’s not a problem in the Mollom API.
While writing a test for some view plugin the other day, I was doing the same thing. I stubbed out everything from ActionView/ActionController which I used (content_tag and url_for and such). Suddenly I realised that wasn’t a good idea.
Rails plugins tests should use the Rails Framework, because the plugins themselves rely on it deeply. To be sure the plugin keeps working while the framework changes, I just have to run my tests, which is exactly what I want.
So I do it this way now:
# from http://github.com/DefV/title_helper/tree/master/test/title_helper_test.rb require 'test/unit' require File.dirname(__FILE__) + '/../../../../config/boot.rb' require File.dirname(__FILE__) + '/../../../../config/environment.rb' class TitleHelperTest < Test::Unit::TestCase def setup @helper = ActionView::Base.new end # Replace this with your real tests. def test_title_method_with_no_title_set assert_equal "foobar", @helper.title(:site_name => 'foobar') end ... end
How do you test your Rails Plugins?
l
Leave a Reply