<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>DogBiscuit</title>
    <description>... mmm, crunchy!</description>
    <link>http://dogbiscuit.org/mdub/weblog</link>
    <language>en-us</language>
    <generator>EvenYetAnotherWeblog</generator>
    <item>
      <title>Spying on your code with RR</title>
      <guid>http://dogbiscuit.org/mdub/weblog/Tech/Programming/Ruby/SpyingOnYourCodeWithRR</guid>
      <pubDate>Wed, 27 May 2009 22:39:00 +1000</pubDate>
      <description><![CDATA[<p>
A while back, Melbourne's own Pete Yandell created <a href='http://notahat.com/not_a_mock/'>Not A Mock</a>, an extension to RSpec that supports <a href='http://xunitpatterns.com/Test%20Spy.html'><em>test-spies</em></a>.  And a damn fine idea it was, too.
</p>
<p>
I've recently discovered that my current favourite stub/mock framework, Brian Takita's <a href='http://github.com/btakita/rr'>RR</a>, can do test-spies too!
</p>
<h3>
Huh?
</h3>
<p>
What's this "spy" business about?  Well, when <em>mocking</em>, <u>before</u> triggering the behaviour you're testing, you set up <em>expectations</em> that a certain methods of collaborating objects will be invoked, with the specified parameters.  Like so:
</p>
<pre>
describe TransferEverything do

  before do
    @account1 = Account.new
    @account2 = Account.new
    @transfer = TransferEverything.new(:from =&gt; @account1, :to =&gt; @account2)
  end

  describe &quot;#execute&quot; do

    it &quot;moves all funds from one account to the other&quot; do

      all_the_money = 1.42
      stub(@account1).balance { all_the_money }

      mock(@account1).withdraw(all_the_money)   # &lt;= set expectations
      mock(@account2).deposit(all_the_money)

      @transfer.execute                         # &lt;= execute
      
    end                                         # &lt;= verify expectations

  end

end
</pre>
<p>
The expectations are typically verified auto-magically, by the mocking framework, at the end of your test. 
</p>
<h3>
The spy alternative
</h3>
<p>
Setting up expectations <em>before</em> a call always feels clumsy.  Using a test <em>spy</em> makes tests flow more naturally:
</p>
<ol>
<li>
<strong>Stub</strong> out collaborators, setting up canned responses where required.
</li>
<li>
<strong>Execute</strong> the code you're testing.
</li>
<li>
<strong>Verify</strong> the results, including both:
</li>
<ul>
<li>
the outputs (return values, or resulting state)
</li>
<li>
the interactions (ie. the method-invocations you expected your fake collaborators to receive).
</li>
</ul>
</ol>
<p>
Fur egg-sample:
</p>
<pre>
describe TransferEverything do

  # ...

  describe &quot;#execute&quot; do

    it &quot;moves all funds from one account to the other&quot; do

      all_the_money = 1.42
      stub(@account1).balance { all_the_money }
      stub(@account1).withdraw
      stub(@account2).deposit

      @transfer.execute

      @account1.should have_received.withdraw(all_the_money)
      @account2.should have_received.deposit(all_the_money)

    end

  end

end
</pre>
<p>
One thing I find particularly useful about this technique is the ability to execute code in a setup block, then verify the various aspects of it's behaviour in separate test-cases.
</p>
<pre>
describe TransferEverything do

  # ...

  describe &quot;#execute&quot; do

    before do
      @all_the_money = 1.42
      stub(@account1).balance { all_the_money }
      stub(@account1).withdraw
      stub(@account2).deposit
      @transfer.execute
    end

    it &quot;withdraws all funds from source account&quot; do
      @account1.should have_received.withdraw(all_the_money)
    end

    it &quot;deposits funds in receiving account&quot; do
      @account2.should have_received.deposit(all_the_money)
    end

  end

end
</pre>
<p>
This results in smaller, more coherent test-cases.  
</p>
<h3>
Using RR test-spies in RSpec
</h3>
<p>
If you're using RSpec, you'll need to use the adapter class that comes with RR, rather than the one that comes with RSpec.  That is, in your <tt>spec_helper.rb</tt>, do this, which provides access to the <tt>have_received</tt> matcher.
</p>
<pre>
require 'rr'
Spec::Runners.configure do |config|
  config.mock_with RR::Adapters::Rspec
end
</pre>
<h3>
Spying on Java
</h3>
<p>
Honourable mention: if you're lucky (*cough*) enough to be coding Java, I HIGHLY recommended <a href='http://mockito.org'>Mockito</a>, which also implements test-spies, and is easily the best Java mocking/stubbing library around.
</p>
]]></description>
    </item>
    <item>
      <title>ReadOnlyFormBuilder</title>
      <guid>http://dogbiscuit.org/mdub/weblog/Tech/Programming/Ruby/Rails/ReadOnlyFormBuilder</guid>
      <pubDate>Sat, 08 Mar 2008 22:00:00 +1100</pubDate>
      <description><![CDATA[<p>
For RubyOnRails developers, <a href='http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html'><tt>form_for</tt> and <tt>fields_for</tt></a>
are the accepted way of DRYing up form templates. You know the deal; you code
</p>
<pre>
&lt;% form_for :customer, :url =&gt; customers_path() do |customer_form| %&gt;
  &lt;p&gt;
    &lt;label&gt;Name:&lt;/label&gt; 
    &lt;%= customer_form.text_field :first_name, :size =&gt; 15 %&gt;
    &lt;%= customer_form.text_field :last_name, :size =&gt; 20 %&gt;
  &lt;/p&gt;
  ... etc ...
&lt;% end %&gt;
</pre>
<p>
and you get
</p>
<pre>
&lt;form action=&quot;/customers&quot; method=&quot;post&quot;&gt;
  &lt;p&gt;
    &lt;label&gt;Name:&lt;/label&gt; 
    &lt;input id=&quot;customer_first_name&quot; name=&quot;customer[first_name]&quot; size=&quot;15&quot; type=&quot;text&quot; /&gt;
    &lt;input id=&quot;customer_last_name&quot; name=&quot;customer[last_name]&quot; size=&quot;20&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;
  &lt;/p&gt;
  ... etc ...
&lt;/form&gt;
</pre>
<p>
Rails generates sensible field names and ids for you, and slurps existing values out of the model object.  So far, so good.
</p>
<p>
Lately, I've taken to using the same trick when presenting data, not just when editing it.  So, whereas before I might have written:
</p>
<pre>
  &lt;p&gt;
    &lt;label&gt;Name:&lt;/label&gt; 
    &lt;span id=&quot;customer_first_name&quot;&gt;&lt;%= h @customer.first_name %&gt;&lt;/span&gt;
    &lt;span id=&quot;customer_last_name&quot;&gt;&lt;%= h @customer.last_name %&gt;&lt;/span&gt;
  &lt;/p&gt;
  ... etc ...
</pre>
<p>
I'll now code it up as:
</p>
<pre>
&lt;% fields_for :customer, :builder =&gt; ReadOnlyFormBuilder do |customer_form| %&gt;
  &lt;p&gt;
    &lt;label&gt;Name:&lt;/label&gt; 
    &lt;%= customer_form.text_field :first_name, :size =&gt; 15 %&gt;
    &lt;%= customer_form.text_field :last_name, :size =&gt; 20 %&gt;
  &lt;/p&gt;
  ... etc ...
&lt;% end %&gt;
</pre>
<p>
and get the same output.  (In case you're wondering, the ids are there to help with automated testing).
</p>
<p>
Note the similarity between the last code snippet and the first one on this page; apart from the first line they're
indentical. Usually, I'll put the field-declarations themselves in a partial that's shared between "new", "edit" and "show"
actions.  That way, your "show" page automatically gets identical layout to the others, just with raw values in place of editable fields.
</p>
<p>
The ReadOnlyFormBuilder class itself it fairly straightforward - I'm planning to wrap it up into a plugin sometime soon.  In the meantime, the implementation of text_field looks something like this:
</p>
<pre>
def text_field(attribute, options={})
  content_tag(&quot;span&quot;, html_escape(value_of(attribute)), :id =&gt; &quot;#{@object_name}_#{attribute}&quot;)
end

def value_of(attribute)
  value = model.send(attribute)
end

def model
  @object || @template.instance_variable_get(&quot;@#{@object_name}&quot;)
end
</pre>
]]></description>
    </item>
    <item>
      <title>Rake profiling</title>
      <guid>http://dogbiscuit.org/mdub/weblog/Tech/Programming/Ruby/RakeProfiling</guid>
      <pubDate>Fri, 01 Feb 2008 00:00:00 +1100</pubDate>
      <description><![CDATA[<p>
Where's the bottleneck in your <a href='http://rake.rubyforge.org'>Rake</a> build?  Let's find out.  Drop (or include) this in your Rakefile:
</p>
<pre>
module Rake
  class Task
    def execute_with_timestamps(*args)
      start = Time.now
      execute_without_timestamps(*args)
      execution_time_in_seconds = Time.now - start
      printf(&quot;** %s took %.1f seconds\n&quot;, name, execution_time_in_seconds)
    end
    
    alias :execute_without_timestamps :execute
    alias :execute :execute_with_timestamps 
  end
end
</pre>
]]></description>
    </item>
    <item>
      <title>method_missing magic - emulating Groovy's "it" in Ruby</title>
      <guid>http://dogbiscuit.org/mdub/weblog/Tech/Programming/Ruby/MethodMissingMagic</guid>
      <pubDate>Mon, 02 Oct 2006 13:55:00 +1000</pubDate>
      <description><![CDATA[<p>
Inspired variously by:
<ul>
<li>
<a href='http://blogs.pragprog.com/cgi-bin/pragdave.cgi/Tech/Ruby/ToProc.rdoc'>Symbol#to_proc</a>
</li>
<li>
Nat Pryce's articles on <a href='http://nat.truemesh.com/archives/000535.html'>Higher-Order Messaging in Ruby</a>
</li>
<li>
Groovy's <a href='http://groovy.codehaus.org/Closures'>implied "<tt>it</tt>" closure-parameter</a>
</li>
</ul>
</p>
<p>
I've cooked up a shortcut for generating simple blocks, meaning that rather
than 
</p>
<pre>
people.select { |x| x.name.length &gt; 10 }
</pre>
<p>
I can write such things as:
</p>
<pre>
people.select(&amp;its.name.length &gt; 10)
</pre>
<p>
<em> Disclaimer: I think this is more "cool hack" than useful tool; it's
probably too much of an <a href='http://www.eaves.org/blog-archive/000071.html'>alien
artifact</a> to be useful in
real life.  And it's not generally applicable, like "<tt>it</tt>" in Groovy.  And
really, it's not <strong>that</strong> much more verbose to use a block. Aaaaaanyway
...</em>
</p>
<p>
The trick is that the above is parsed as
</p>
<pre>
people.select(&amp;(its.name.length.&gt;(10)))
</pre>
<p>
The "<tt>its</tt>" method creates a <tt>MessageBuffer</tt> object, which records the
messages (method invocations) sent it's way:
</p>
<pre>
irb(main):001:0&gt; require 'message_buffer'
=&gt; true
irb(main):002:0&gt; its
=&gt; #&lt;MessageBuffer:0x6b40b44 @messages=[]&gt;
irb(main):003:0&gt; its.name.length &lt; 10
=&gt; #&lt;MessageBuffer:0x6b3e678 @messages=[[:name], [:length], [:&lt;, 10]]&gt;
</pre>
<p>
Now, the "&" operator coerces it's argument to a <tt>Proc</tt>, and
<tt>MessageBuffer#to_proc</tt> generates a <tt>Proc</tt> that replays all the recorded
messages.  Q.E.D.  
</p>
<p>
The full source-code is fairly short, so I'll include it inline:
</p>
<pre>
class MessageBuffer 

  instance_methods.each do |m|
    undef_method m unless m =~ /^(__|respond_to|inspect)/ 
  end
  
  def initialize
    @messages = []
  end

  def method_missing(*message)
    @messages &lt;&lt; message        # record the message
    self                        # return self so we can keep recording
  end
  
  def __replay_all_messages__(obj)
    @messages.inject(obj) do |obj, message|
      obj.__send__(*message)
    end 
  end
  
  def to_proc
    proc { |x| __replay_all_messages__(x) }
  end

end

def its
  MessageBuffer.new
end
</pre>
<p>
<hr/>
</p>
<p>
<em>Update: Florian Gross suggested a better way to replay recorded
messages, using <code>inject</code>, and I've updated the code accordingly.
</em>
</p>
]]></description>
    </item>
    <item>
      <title>Presentation on Ruby/Rails at EJA</title>
      <guid>http://dogbiscuit.org/mdub/weblog/Tech/Programming/Ruby/Ruby@EJA</guid>
      <pubDate>Thu, 28 Sep 2006 16:10:00 +1000</pubDate>
      <description><![CDATA[<p>
A couple of months ago I gave a presentation on
<a href='http://www.ruby-lang.org'>Ruby</a> and <a href='http://rubyonrails.org'>Rails</a> to a
<a href='http://www.enterprisejava.org.au/'>local Java user-group</a>.  My slides are
now online:
</p>
<ul class="sparse">
<li>
<a href='http://dogbiscuit.org/mdub/weblog/../presentations/Ruby@EJA/'>Ruby@EJA</a>
</li>
</ul>
<p>
It contains a few examples showing how expressive Ruby can be, when
compared to Java.
</p>
]]></description>
    </item>
    <item>
      <title>Tracing with a dynamic Proxy, in Ruby</title>
      <guid>http://dogbiscuit.org/mdub/weblog/Tech/Programming/Ruby/DynamicTracingProxy</guid>
      <pubDate>Thu, 12 May 2005 13:45:00 +1000</pubDate>
      <description><![CDATA[<p>
Recently, I was writing a (<a href='http://ruby-lang.org'>Ruby</a>) script to sync
email between two IMAP servers.  My unit-tests were all working, but
something was going screwy when I plugged in a real server.
</p>
<p>
I wanted to be able to trace the conversation with the IMAP server (or at
least, Ruby's IMAP API), to see what was going on.  Initially, I started
sprinkling tracing statements throughout my code, until I realised that it
was going to be easier to define a simple "tracing proxy", and wrap it
around the object I wanted to trace:
</p>
<pre>
imap_handle = TracingProxy.new(imap_handle, $stderr)

# ... do stuff with imap_handle ...
</pre>
<p>
It turned out to be straightforward to implement:
</p>
<pre>
class TracingProxy

  def initialize(obj, dest) 
    @obj = obj
    @dest = dest
  end

  def method_missing(symbol, *args)
    arglist = args.map { |a| a.inspect }.join(', ')
    @dest.puts &quot;#{symbol}(#{arglist})&quot;
    rval = @obj.send(symbol, *args)
    @dest.puts &quot;&gt;&gt; #{rval.inspect}&quot;
    rval
  end
  
end
</pre>
<p>
<a href='http://www.ruby-doc.org/core/classes/Kernel.html#M001729'><tt>method_missing</tt></a>
is a fallback method invoked when the called method isn't found - it's
great for implementing dynamic proxies.  There's nothing particularly
ground-breaking going on here - this kind of trick is fairly common in
Ruby-land.
</p>
<p>
My point is: implementing a dynamic-proxy for tracing was so <strong>easy</strong> in Ruby
that I actually did it.  I could have done something similar in Java, using
<tt>java.lang.reflect.Proxy</tt>, or <a href='http://cglib.sourceforge.net/'>cglib</a> - but I
most likely wouldn't have bothered.
</p>
<p>
In Ruby, implementing the proxy made my life easier, not harder.  Ruby
<u>encourages me to produce better designs</u>.
</p>
]]></description>
    </item>
    <item>
      <title>Refactoring "support" for Ruby?</title>
      <guid>http://dogbiscuit.org/mdub/weblog/Tech/Programming/Ruby/RubyMethodRenamed</guid>
      <pubDate>Sun, 10 Apr 2005 23:00:00 +1000</pubDate>
      <description><![CDATA[<p>
These days, there a number of pretty damn good IDEs for Java, with features
like intelligent code-completion (aka "intellisense") and automated
refactorings.  I was a late-starter with IDEs, myself, but even just over
the past year I've become annoyingly dependent on some of those IDE
features.
</p>
<p>
Such features depend quite heavily on gleaning data-type information from
the code, which is fine for languages like Java and C#.  But in
dynamically-typed languages like <a href='http://ruby-lang.org'>Ruby</a>, we don't have
that type info, so things like method-name completion and automated
renaming become impossible.  (Or so I thought).
</p>
<h3>
Stealing a trick from SmallTalk
</h3>
<p>
It's been puzzling me that there isn't better refactoring support for Ruby,
given that the whole concept of <a href='http://www.refactoring.com'>refactoring</a>
grew out of the SmallTalk community, in the first place.  Or more
accurately, I've been confused about how automated refactoring could be
possible in a dynamic language like SmallTalk.  
</p>
<p>
Then, recently, I stumbled across a paper describing "<a href='http://st-www.cs.uiuc.edu/~droberts/tapos/TAPOS.htm'>A Refactoring Tool
for Smalltalk</a>", which
contains the following explanation:
</p>
<blockquote>
The Refactoring Browser uses <u>method wrappers</u> to collect runtime
information. These wrappers are activated when the wrapped method is
called and when it returns. The wrapper can execute an arbitrary block of
Smalltalk code. To perform the rename method refactoring dynamically, the
Refactoring Browser renames the initial method and then puts a method
wrapper on the original method. As the program runs, the wrapper detects
sites that call the original method. Whenever a call to the old method is
detected, the method wrapper suspends execution of the program, goes up
the call stack to the sender and changes the source code to refer to the
new, renamed method. Therefore, <u>as the program is exercised</u>, it
converges towards a correctly refactored program.
</blockquote>
<p>
Ah-ha!  Cunning.
</p>
<h3>
The Ruby version
</h3>
<p>
As it turns out, we can do much the same thing in Ruby ... leaving aside
the "go up the call stack and change the source code" part.
</p>
<p>
Here's the supporting code:
</p>
<pre>
def method_renamed(h)
  old_name = h.keys[0].to_sym
  new_name = h.values[0].to_sym
  define_method(old_name) { |*args|
    file, line = caller[1].split(':')
    warning = &quot;##{old_name} renamed to ##{new_name}&quot;
    $stderr.puts &quot;#{file}:#{line}: #{warning}&quot;
    send(new_name, *args)
  }
end
</pre>
<p>
Okay, here's a method I want to rename:
</p>
<pre>
class LinkPanel

  def render
    # ... 
  end

end
</pre>
<p>
When I rename it, I also record the change using <tt>method_renamed</tt>:
</p>
<pre>
class LinkPanel

  method_renamed :render =&gt; :to_html

  def to_html
    # ... 
  end

end
</pre>
<p>
Now, I run my tests, and calls to the renamed method result in warnings:
</p>
<pre>
/home/mikew/eyaw/sidebar.rb:229: #render renamed to #to_html
</pre>
<p>
With a single key-chord in my <a href='http://www.gnu.org/software/emacs/emacs.html'>Ruby
IDE</a>, I can jump directly to
the source-code in question, and fix up the call.  I imagine that an
ever-so-slightly-more intelligent IDE could complete the refactoring,
applying the rename to the call-site automatically!  Later on, when I'm
confident that everything has been cleaned up, I'll go back and remove that
<tt>method_renamed</tt> alias.
</p>
<p>
There's more to refactoring than just renaming stuff, of course.  I think
the "dynamic analysis" trick would be useful to support other refactorings,
too ... though I haven't tried it yet.
</p>
<p>
Proviso: this approach relies on actually running the code, preferably from
tests.  As the original paper says:
</p>
<blockquote>
.. the refactoring is only as good as your test suite. If there are
pieces of code that are not executed, they will never be analyzed, and
the refactoring will not be completed ...
</blockquote>
]]></description>
    </item>
  </channel>
</rss>
