tag:www.rhnh.net,2008:/dm-moreDm More - Xavier Shay's Blog2008-11-14T18:47:46ZEnkiXavier Shaynotreal@rhnh.nettag:www.rhnh.net,2008:Post/7892008-11-14T18:47:00Z2008-11-14T18:47:46ZUnique data in dm-sweatshop<p><code>dm-sweatshop</code> is how you set up test data for your datamapper apps. Standard practice is to generate random data that follows a pattern:</p><table class="CodeRay"><tr>
<td class="line_numbers" title="click to toggle" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<tt>
</tt>2<tt>
</tt>3<tt>
</tt>4<tt>
</tt>5<tt>
</tt></pre></td>
<td class="code"><pre ondblclick="with (this.style) { overflow = (overflow == 'auto' || overflow == '') ? 'visible' : 'auto' }"><span class="co">User</span>.fix {{<tt>
</tt> <span class="sy">:login</span> => <span class="rx"><span class="dl">/</span><span class="ch">\w</span><span class="k">+</span><span class="dl">/</span></span>.gen<tt>
</tt>}}<tt>
</tt><tt>
</tt>new_user = <span class="co">User</span>.gen<tt>
</tt></pre></td>
</tr></table>
<p>Let’s not now debate whether or not random data in tests is a good idea. What’s more important is that the above code should make you uneasy if login is supposed to be unique. There was a hack in sweatshop that would try recreating the data if you had a uniqueness constraint on login and it was invalid, but it was exactly that: a hack. As of a few days ago (what will be 0.9.7), you need to be more explicit if you want unique data. It’s pretty easy:</p><table class="CodeRay"><tr>
<td class="line_numbers" title="click to toggle" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<tt>
</tt>2<tt>
</tt>3<tt>
</tt>4<tt>
</tt>5<tt>
</tt></pre></td>
<td class="code"><pre ondblclick="with (this.style) { overflow = (overflow == 'auto' || overflow == '') ? 'visible' : 'auto' }">include <span class="co">DataMapper</span>::<span class="co">Sweatshop</span>::<span class="co">Unique</span><tt>
</tt><tt>
</tt><span class="co">User</span>.fix {{<tt>
</tt> <span class="sy">:login</span> => unique { <span class="rx"><span class="dl">/</span><span class="ch">\w</span><span class="k">+</span><span class="dl">/</span></span>.gen }<tt>
</tt>}}<tt>
</tt></pre></td>
</tr></table>
<p>Tada! You can also easily get non-random unique data by providing a block with one parameter. <a href="http://github.com/sam/dm-more/tree/master/dm-sweatshop/README.textile">Check the <span class="caps">README</span></a> for this and other cool things you can do.</p>