<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Clayton Lengel-Zigich &#187; Development</title>
	<atom:link href="http://www.claytonlz.com/category/development/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.claytonlz.com</link>
	<description>Agile Practitioner, CSP, CSPO, CSM in Phoenix, AZ</description>
	<lastBuildDate>Thu, 03 May 2012 17:29:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Using Bundler and Capistrano Behind a Proxy</title>
		<link>http://www.claytonlz.com/2011/06/bundler-capistrano-behind-proxy/</link>
		<comments>http://www.claytonlz.com/2011/06/bundler-capistrano-behind-proxy/#comments</comments>
		<pubDate>Tue, 14 Jun 2011 05:58:08 +0000</pubDate>
		<dc:creator>Clayton</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Ruby On Rails]]></category>
		<category><![CDATA[bundler capistrano deployment proxy]]></category>

		<guid isPermaLink="false">http://www.claytonlz.com/?p=497</guid>
		<description><![CDATA[When you're developing applications for a fortune 50 company, you're bound to run into a problem with their security focused IT department. Recently, I was having trouble deploying a rails application to a server that was sitting behind a proxy. I tried to solve the problem by changing bundler, then by reconfiguring capistrano, but those were both dead ends.]]></description>
			<content:encoded><![CDATA[<p>When you&#8217;re developing applications for a fortune 50 company, you&#8217;re bound to run into a problem with their security focused IT department. Recently, I was having trouble deploying a rails application to a server that was sitting behind a proxy. I tried to solve the problem by changing bundler, then by reconfiguring capistrano, but those were both dead ends.</p>

<h3>Setup Your <code>$http_proxy</code></h3>

<p>I thought that I could edit my <code>.gemrc</code> and that bundler would use those settings, but that didn&#8217;t work. I had been installing gems by using the <code>--http-proxy</code> flag so it seemed like that would work. I had also been contacting the outside world (for git and other things) by setting the <code>http_proxy</code> environment variable, but I was doing so manually each time I needed it, rather than setting it up in my shell&#8217;s rc file. Here&#8217;s how I fixed it.</p>

<p><em>This assumes that the shell you&#8217;re editing belongs to the user that deploys the application in capistrano.</em></p>

<p>1. Add the <code>http_proxy</code> to your shell&#8217;s rc file</p>



<pre>
# bash
export http_proxy=http://proxy.example.com:8080

#tcsh
setenv http_proxy http://proxy.example.com:8080
</pre>



<p>2. Ensure that when you create a new session, the <code>http_proxy</code> environment variable is actually set</p>



<pre>
$&gt; echo $http_proxy

http://proxy.example.com:8080

</pre>



<p>Now, when you deploy with capistrano, the <code>bundle</code> command will the proxy that&#8217;s setup and communication with your gem sources won&#8217;t timeout.</p>]]></content:encoded>
			<wfw:commentRss>http://www.claytonlz.com/2011/06/bundler-capistrano-behind-proxy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Printing PDF HightCharts with wkhtmltopdf and PDFKit</title>
		<link>http://www.claytonlz.com/2011/02/broken-highcharts-wkhtmltopdf/</link>
		<comments>http://www.claytonlz.com/2011/02/broken-highcharts-wkhtmltopdf/#comments</comments>
		<pubDate>Thu, 10 Feb 2011 06:20:51 +0000</pubDate>
		<dc:creator>Clayton</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[highcharts wkhtmltopdf pdfkit]]></category>

		<guid isPermaLink="false">http://www.claytonlz.com/?p=472</guid>
		<description><![CDATA[I have a rails 3 application that&#8217;s using Highcharts the fantastic javascript powered charting library. I&#8217;m also generating PDF versions of some pages using wkhtmltopdf and PDFKit for things like &#8220;download this report&#8221; and what not. Everything was working great, until I noticed that my line charts were being rendered very poorly when I was [...]]]></description>
			<content:encoded><![CDATA[<p>I have a rails 3 application that&#8217;s using <a href="http://www.highcharts.com/">Highcharts</a> the fantastic javascript powered charting library. I&#8217;m also generating <span class="caps">PDF </span>versions of some pages using <a href="http://code.google.com/p/wkhtmltopdf/">wkhtmltopdf</a> and <a href="https://github.com/jdpace/PDFKit"><span class="caps">PDFK</span>it</a> for things like &#8220;download this report&#8221; and what not. </p>

<p>Everything was working great, until I noticed that my line charts were being rendered very poorly when I was viewing a <span class="caps">PDF.</span> As <span class="caps">HTML </span>they look great, but as a <span class="caps">PDF </span>they look like this:</p>

<p><img src="http://www.claytonlz.com/wp-content/uploads/2011/02/Screen-shot-2011-02-09-at-11.05.16-PM-640x344.png" alt="" title="Poorly Rendered Highcharts from wkhtmltopdf" width="640" height="344" class="alignnone size-medium wp-image-473" /></p>

<p>I dug around a bit and found a <a href="http://highslide.com/forum/viewtopic.php?f=9&amp;t=6869">helpful forum post</a> explaining the problem, something to do with how <code>wkhtmltopdf</code> renders opacity. The important part is this (specifically line 7):</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script type<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;text/javascript&quot;</span> charset<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;utf-8&quot;</span><span style="color: #339933;">&gt;</span>
&nbsp;
  <span style="color: #003366; font-weight: bold;">var</span> chart <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Highcharts.<span style="color: #660066;">Chart</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
      chart<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span> renderTo<span style="color: #339933;">:</span> <span style="color: #3366CC;">'container'</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
      <span style="color: #006600; font-style: italic;">// These make it work nicely with wkhtmltopdf</span>
      plotOptions<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span> series<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span> enableMouseTracking<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">,</span> shadow<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">,</span> animation<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span> <span style="color: #009900;">&#125;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
      xAxis<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span> categories<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'Jan'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'Feb'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'Mar'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'Apr'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'May'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'Jun'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'Jul'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'Aug'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'Sep'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'Oct'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'Nov'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'Dec'</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
      series<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#123;</span> data<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #CC0000;">29.9</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">71.5</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">106.4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">129.2</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">144.0</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">176.0</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">135.6</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">148.5</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">216.4</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">194.1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">95.6</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">54.4</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#93;</span>
&nbsp;
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>




<p>Turning off animation, mouse tracking and shadows apparently gives <code>wkhtmltopdf</code> enough to render the chart. When I added that to my charts, I got a chart that looks like this:<br />
<img src="http://www.claytonlz.com/wp-content/uploads/2011/02/Screen-shot-2011-02-09-at-11.18.58-PM-640x348.png" alt="" title="Working wkthmltopdf Highcharts rendering" width="640" height="348" class="alignnone size-medium wp-image-476" /></p>]]></content:encoded>
			<wfw:commentRss>http://www.claytonlz.com/2011/02/broken-highcharts-wkhtmltopdf/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Five Essential Performance Optimization Steps</title>
		<link>http://www.claytonlz.com/2010/09/essential-optimization-steps/</link>
		<comments>http://www.claytonlz.com/2010/09/essential-optimization-steps/#comments</comments>
		<pubDate>Mon, 27 Sep 2010 18:00:10 +0000</pubDate>
		<dc:creator>Clayton</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.claytonlz.com/?p=440</guid>
		<description><![CDATA[Performance optimization of any software project is a mix of art, science, stubbornness and inexplicable improvement. Most developers will spend incredible amounts of time tweaking their application to squeeze out performance gains, regardless of the value they provide. As the old saying goes, given enough optimization rope, developers will quickly hang themselves. Using the following [...]]]></description>
			<content:encoded><![CDATA[<p>Performance optimization of any software project is a mix of art, science, stubbornness and inexplicable improvement. Most developers will spend incredible amounts of time tweaking their application to squeeze out performance gains, regardless of the value they provide. As the old saying goes, given enough optimization rope, developers will quickly hang themselves.</p>

<p>Using the following five steps, you can ensure that the time you spend optimizing your application provides maximum value.</p>

<h3>1. Benchmarking</h3>

<p>Optimizing your application is worthless without a benchmark. You absolutely must have a measurement of performance before you begin so that your changes can be quantified when you are done. I have seen many developers start out with a complaint from a client about a &#8220;slow&#8221; page and then spend a few hours making changes only to conclude with &#8220;it seems a lot faster now&#8221;. If you&#8217;re optimizing a rails application, something like <a href="http://www.newrelic.com/">New Relic&#8217;s</a> <span class="caps">RPM </span>is a great choice. Another tool I&#8217;ve had success with is brynary&#8217;s <a href="http://github.com/brynary/rack-bug">rack-bug</a>.</p>

<h3>2. Set a Timebox</h3>

<p>Once you&#8217;ve recorded benchmarks for the problem areas of your application you need to determine what specifically is wrong and how to fix the problem. Since it&#8217;s possible to spend hours upon hours of time under the directive of &#8220;performance improvement&#8221; you need to set a hard limit on the time you spend optimizing. Two timeboxes should be used, one to locate the specifics of the problem and another to fix them.</p>

<h3>3. Similarity of Environments</h3>

<p>The vast majority of performance issues will be discovered by real users performing real tasks in a production environment. In a rails application, the behavior of the development environment is far different from that of the production environment, so why would you optimize in anything but the production environment? Of course you can&#8217;t optimize on the live production application, but you can setup a similar environment that behaves like the live production environment. Just recently I spent an hour optimizing a slow page and actually gained an 80% improvement, the only problem was, in production the page was slow for a completely different reason. Talk about a tough conversation, having to go back to the client and explain that my previous detailed explanation and assurance that the problem was solved was instead all wrong.</p>

<h3>4. Accurate Dataset</h3>

<p>How many times have you implemented a feature, ran it through some tests, demo&#8217;d to the client, deployed it to staging only to find that when it makes it to production it is impossibly slow to the point of being useless? If your production environment has a huge database with a hundred thousand rows and a few hundred concurrent users, testing on your development machine with 10 rows in the database is a waste of time. Make sure that the dataset on which you are testing your improvements accurately reflects your production dataset.</p>

<h3>5. Low-hanging Fruit and Small Victories</h3>

<p>Since you will have a fixed amount of time in which to optimize, you need to take small wins and get the low-hanging fruit when possible. Maybe the best solution to your problem is to drastically change the application&#8217;s design garnering a big boost to performance. However, if that route takes you beyond your timebox maybe a few database indexes and an optimized query are all you can afford. Always remember that a small performance improvement is better than no improvement and that the small stuff always adds up.</p>

<h3><span class="caps">BONUS</span> Stakeholders Care About Value</h3>

<p>When a report of a slow feature comes in, make sure that you evaluate the time and effort it will take to implement the improvement. Communicate this with the client, product owner and/or stakeholders so that they can evaluate the value they&#8217;ll receive from the time you spend. If the feature in question is used infrequently it might not be worth the time or cost. Conversely, performance optimization should not always be viewed as something done for free. If an application has grown in size beyond what was originally envisioned, it is perfectly reasonable to charge your client for performance enhancements.</p>

<p>Don&#8217;t be like most developers, keep these steps in mind and make your next performance optimization session a success.</p>]]></content:encoded>
			<wfw:commentRss>http://www.claytonlz.com/2010/09/essential-optimization-steps/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Common ThinkingSphinx Configuration Problems</title>
		<link>http://www.claytonlz.com/2010/09/thinkingsphinx-conf-problems/</link>
		<comments>http://www.claytonlz.com/2010/09/thinkingsphinx-conf-problems/#comments</comments>
		<pubDate>Sun, 19 Sep 2010 05:19:13 +0000</pubDate>
		<dc:creator>Clayton</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Ruby On Rails]]></category>

		<guid isPermaLink="false">http://www.claytonlz.com/?p=432</guid>
		<description><![CDATA[I have recently added full-text search to two Rails projects using Sphinx and the ThinkingSphinx gem. While I have been extremely impressed with both Sphinx and ThinkingSphinx, I did stumble along the way a few times trying to get everything setup and working consistently. On both projects I had setup delta indexing so that my [...]]]></description>
			<content:encoded><![CDATA[<p>I have recently added full-text search to two Rails projects using <a href="http://www.sphinxsearch.com/">Sphinx</a> and the <a href="http://freelancing-god.github.com/ts/en/">ThinkingSphinx</a> gem. While I have been extremely impressed with both Sphinx and ThinkingSphinx, I did stumble along the way a few times trying to get everything setup and working consistently. On both projects I had setup <a href="http://freelancing-god.github.com/ts/en/deltas.html">delta indexing</a> so that my very large search indexes would not need to be rebuild but once per day. On one of the projects I also added <a href="http://mmonit.com/monit/">monit</a> to keep <code>searchd</code> running, monitoring the process once every few minutes.</p>

<blockquote>Updated: 9/23/2010</blockquote>

<p>Installing Sphinx and the initial setup of ThinkingSphinx were straightforward and relatively simple, however, I spent about two weeks debugging what turned out to be a collection of small problems that, together, made me think I had gone terribly wrong in choosing Sphinx for my full-text search needs.</p>

<h3><code>searchd</code> Binary Path</h3>

<p><strong>Problem</strong><br />
You try and run some of the ThinkingSphinx rake tasks, but they fail because ThinkingSphinx can&#8217;t find the required Sphinx binaries.</p>

<p><strong>Solution</strong><br />
ThinkingSphinx needs to be able to start and stop sphinx when deploying. If you ssh into your server using the username of the user who runs your rails application (deploy in my case) and type <code>which searchd</code> at the command prompt, you should see something similar to <code>/usr/bin/searchd</code> although it will vary depending on how you installed Sphinx.</p>

<p>In your production version of the <code>config/sphinx.yml</code> file, set the <code>bin_path</code> configuration option. Let&#8217;s say that <code>which searchd</code> returns <code>/usr/local/bin/sphinx/bin/searchd</code> you&#8217;d want your <code>sphinx.yml</code> to contain the following:</p>


<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">production:
  bin_path: &quot;/usr/local/bin/sphinx/bin&quot;</pre></div></div>





<h3><code>searchd</code> pid File</h3>

<p><strong>Problem</strong><br />
You&#8217;ve setup Monit to monitor <code>searchd</code> but Monit is unable to monitor or restart <code>searchd</code>. In my case, the location of the pid file was not what I was expecting so Monit could not monitor the <code>searchd</code> process. </p>

<p><strong>Solution</strong><br />
In order to have Monit monitor the <code>searchd</code> process, it&#8217;s necessary to specify the location of the <code>search</code> pid file in your monit configuration. When you use ThinkingSphinx to build your Sphinx configuration file, the location of your pid file is specified in the resulting <code>production.sphinx.conf</code>. I decided that I wanted to specify the location of the <code>searchd</code> pid file so that others wouldn&#8217;t have to go digging through the auto generated configuration file to find it.</p>


<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">production:
  bin_path: &quot;/usr/local/bin/sphinx/bin&quot;
  pid_file: &quot;/home/deploy/apps/my_rails_app/shared/log/searchd.pid&quot;</pre></div></div>




<p>My <code>/etc/monit.d/sphinx</code> configuration file:<sup class="footnote"><a href="#fn1">1</a></sup></p>


<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">  check process searchd with pidfile /home/deploy/apps/my_rails_app/current/log/searchd.production.pid 
  start program = &quot;/usr/local/bin/start_sphinx&quot; as uid deploy 
  stop program = &quot;/usr/local/bin/stop_sphinx&quot; as uid deploy</pre></div></div>




<p>The <code>/usr/local/bin/start_sphinx</code> file used to start <code>searchd</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">  #!/bin/bash
  export PATH=&quot;$PATH:/usr/local/bin&quot;
&nbsp;
  cd /home/deploy/apps/my_rails_app/current &amp;&amp; RAILS_ENV=production /usr/bin/rake thinking_sphinx:index
  cd /home/deploy/apps/my_rails_app/current &amp;&amp; RAILS_ENV=production /usr/bin/rake thinking_sphinx:start &gt; log/sphinx.log 2&gt;&amp;1</pre></div></div>




<p>The <code>/usr/local/bin/stop_sphinx</code> file used to stop <code>searchd</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">  #!/bin/bash
  export PATH=&quot;$PATH:/usr/local/bin&quot;
&nbsp;
  cd /home/deploy/apps/my_rails_app/current &amp;&amp; RAILS_ENV=production /usr/bin/rake thinking_sphinx:stop &gt; log/sphinx.log 2&gt;&amp;1</pre></div></div>






<h3>Index File Location</h3>

<p><strong>Problem</strong><br />
You&#8217;ve deployed your application and build the index. A <code>cron</code> job has been setup to rebuild the index nightly. You notice that when you deploy your application, your indexed results seem to be missing.</p>

<p><strong>Solution</strong><br />
The index files that Sphinx builds and uses should be kept in a shared directory that is available across multiple deploys. Using the typical capistrano setup a good place would be <code>/home/deploy/apps/my_rails_app/shared</code>. By default ThinkingSphinx will store these in <code>RAILS_ROOT/db/sphinx/ENVIRONMENT</code> which is fine in development, but not in production.</p>

<p>First, create a directory in your shared folder on production:</p>

<p><code>$&gt; mkdir /home/deploy/apps/my_rails_app/shared/db</code></p>

<p>Then, if your capistrano deployment recipe for production, symlink the shared db path to current release:</p>


<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">  run <span style="color:#996600;">&quot;ln -nsf  #{shared_path}/db/sphinx/production  #{release_path}/db/sphinx/production&quot;</span></pre></div></div>




<p>Finally, tell ThinkingSphinx to use the shared path for the Sphinx&#8217;s index files.</p>


<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">production:
  bin_path: &quot;/usr/local/bin/sphinx/bin&quot;
  pid_file: &quot;/home/deploy/apps/my_rails_app/shared/log/searchd.pid&quot;
  searchd_file_path: &quot;/home/deploy/apps/my_rails_app/shared/db/sphinx/production&quot;</pre></div></div>




<h3>Permissions</h3>

<p><strong>Problem</strong><br />
The files being created by Sphinx are owned by root and cannot be modified by the user running the ThinkingSphinx rake tasks, usually deploy. This often comes up when delta indexing is being used and the delta indexes are being modified or merged back into the full index.</p>

<p><strong>Solution</strong><br />
You should start and stop <code>searchd</code> using the ThinkingSphinx rake tasks. This will ensure that <code>searchd</code> is started by a user who can later modify the index files if needed. If you are using Monit, make sure you setup your Monit configuration to start or restart the <code>searchd</code> process as the same user who runs the ThinkingSphinx rake tasks.</p>

<p>This is accomplished in my Monit configuration file by using <code>as uid deploy</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">  start program = &quot;/usr/local/bin/start_sphinx&quot; as uid deploy 
  stop program = &quot;/usr/local/bin/stop_sphinx&quot; as uid deploy</pre></div></div>




<h3>Monit Restarts <code>searchd</code> Before Rebuilding is Complete</h3>

<p><strong>Problem</strong><br />
When rebuilding your index, Monit restarts <code>searchd</code> before the index is rebuilt.</p>

<p><strong>Solution</strong><br />
While there are ways to pause Monit for certain services, I found the easiest way to solve this problem was to increase the frequency at which Monit monitors my <code>searchd</code> process. Given the traffic of your site and required uptime of the search index, this solution may not be for you. For me the magic frequency was every three minutes.</p>

<h3>Missing Configuration File</h3>

<p><strong>Problem</strong><br />
When you deploy and build your index and configuration file Sphinx appears to be working, the next time you deploy, your log file fills up with errors about a missing configuration file.</p>

<p><strong>Solution</strong><br />
This one is an easy fix. In the ThinkingSphinx documentation, the deployment strategy is simple.</p>

<blockquote>
Essentially, the following steps need to be performed for a deployment:<br />
  <ul>
    <li>stop Sphinx searchd (ensure it&#8217;s running)</li>
    <li>generate Sphinx configuration</li>
    <li>start Sphinx searchd</li>
    <li>ensure index is regularly rebuilt</li>
  </ul>
</blockquote>

<p>Make sure that part of your deploy process makes a call to the <code>thinking_sphinx:configure</code> rake task. This will regenerate the sphinx configuration file each time you deploy.</p>

<h3>Rebuilding My Index is Too Slow!</h3>

<p><strong>Problem</strong><br />
Your index has many thousands of records. Running <code>rake thinking_sphinx:rebuild</code> works great, but it&#8217;s very slow.</p>

<p><strong>Solution</strong><br />
I recently found out about the <code>thinking_sphinx:reindex</code> rake task. On my sphinx installation with ~115,000 indexed records, <code>reindex</code> is significantly faster than <code>rebuild</code>, so much so that it can be run on an hourly basis to keep my delta indexes from becoming too large.</p>

<p class="footnote" id="fn1"><sup>1</sup> Hat tip to <a href="http://www.christopherirish.com/">Chris Irish</a> for the Monit configuration and start/stop scripts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.claytonlz.com/2010/09/thinkingsphinx-conf-problems/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Zero To Tested With Cucumber and Factory Girl</title>
		<link>http://www.claytonlz.com/2010/03/zero-to-tested-with-cucumber-and-factory-girl/</link>
		<comments>http://www.claytonlz.com/2010/03/zero-to-tested-with-cucumber-and-factory-girl/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 17:30:35 +0000</pubDate>
		<dc:creator>Clayton</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Ruby On Rails]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.claytonlz.com/?p=381</guid>
		<description><![CDATA[Get your project from zero to tested leveraging the power of Cucumber and Factory Girl Testing can be a daunting task, especially for developers who are new to Rails. It sounds like a great idea, but where do you start? What do you test? What don&#8217;t you test? For many developers, the hardest part of [...]]]></description>
			<content:encoded><![CDATA[<h3>Get your project from zero to tested leveraging the power of Cucumber and Factory Girl</h3>

<p>Testing can be a daunting task, especially for developers who are new to Rails. It sounds like a great idea, but where do you start? What do you test? What don&#8217;t you test? For many developers, the hardest part of testing is jumping in and getting your feet wet. Luckily, Cucumber makes getting started with testing easy, you&#8217;ll be testing your code form top to bottom in no time.</p>

<h4>What is Cucumber?</h4>

<p>Cucumber, in simple terms, is a framework for writing human-readable, meaningful tests that allow you to test the full functionality of your Rails project from database access to business logic to what&#8217;s displayed in your views.</p>

<p>From the <a href="http://cukes.info">Cucumber Wiki</a>:</p>

<blockquote><p>Cucumber lets software development teams describe how software should behave in plain text. The text is written in a business-readable domain-specific language and serves as documentation, automated tests and development-aid &#8211; all rolled into one format.</p></blockquote>

<p>When you write your tests with Cucumber you get full-stack automated tests, documentation and a tool to help you communicate with your product owner.</p>

<h4>Who&#8217;s the Factory Girl?</h4>

<p><a href="http://robots.thoughtbot.com/post/159807023/waiting-for-a-factory-girl">Factory Girl</a> is a fixture replacement for Rails that allows you to create meaningful objects for use in your tests.</p>

<p>From the <a href="http://github.com/thoughtbot/factory_girl">Factory Girl Github Page</a>:</p>

<blockquote><p>factory_girl is a fixtures replacement with a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute hashes, and stubbed objects), and support for multiple factories for the same class (user, admin_user, and so on), including factory inheritance.</p></blockquote>

<p>When you use Factory Girl in conjunction with Cucumber you can simplify complex test setup and use real objects from the database, not brittle mocks.</p>

<h4>Getting Setup</h4>

<p>Getting your project setup with Cucumber and Factory Girl is pretty straightforward. First, you&#8217;ll need a few gems installed:</p>



<pre lang="">

    sudo gem install cucumber-rails
    sudo gem install webrat
    sudo gem install thoughtbot-factory_girl --source=http://gemcutter.org

</pre>



<p class="note">Note: As of 0.5.0 the Rails specific functionality was extracted from the cucumber gem into the cucumber-rails gem</p>

<p>Cucumber comes pre-packaged with some generators for getting your project ready for testing. From the root of your Rails project, run the generator:</p>



<pre>

    ruby script/generate cucumber --webrat --rspec

</pre>



<p>You&#8217;ll notice that we&#8217;re passing a couple of flags to the generator, <code>--webrat</code> specifies that we want to use webrat as our automated browser and <code>--rspec</code> specifies that we want to use rspec as our test framework. If you don&#8217;t pass these options Cucumber will guess which options you want based on the gems which you have installed.</p>

<p>After running the generator, you will see some output about the files that were created:</p>


<pre>

    create  config/cucumber.yml
    create  config/environments/cucumber.rb
    create  script/cucumber
    create  features/step_definitions
    create  features/step_definitions/web_steps.rb
    create  features/support
    create  features/support/env.rb
    create  features/support/paths.rb
    create  lib/tasks
    create  lib/tasks/cucumber.rake

</pre>



<p>Here&#8217;s a brief description of what some of the important files do:</p>

<p>*<tt>config/cucumber.rb</tt>*: This is your cucumber environment, similar to <code>production.rb</code> or <code>development.rb</code>. Typically you&#8217;ll add cucumber specific <code>config.gem</code> directives and similar &#8220;cucumber only&#8221; items in here.</p>

<p>*<tt>features/step_definitions/web_steps.rb</tt>*: These are the webrat steps that you get for free with Cucumber and Webrat.</p>

<p>*<tt>features/support/env.rb</tt>*: This file has Cucumber specific setup and configuration options. This changes often, so it&#8217;s recommended to not alter this file directly, but to create your own custom <code>env.rb</code> (e.g. <code>custom_env.rb</code>).</p>

<p>*<tt>features/support/paths.rb</tt>*: Cucumber needs to be aware of the custom routes in your application that you plan on using when testing, this is where they are specified.</p>

<h4>Cucumber from 10,000ft</h4>

<p>Now that you&#8217;ve got your project configured to use Cucumber, let&#8217;s go over a high level view of the general concept of testing with Cucumber.</p>

<p>Cucumber uses &#8220;Features&#8221; to describe the functionality of your application. Features, stored in the <code>features</code> directory, are written in a simple human-readable format called <a href="http://wiki.github.com/aslakhellesoy/cucumber/gherkin">Gherkin</a>. The &#8220;Steps&#8221; in your feature files that describe the functionality of your application are backed up by step files in the <code>features/step_definitions</code> directory. The step files act like translations between the human-readable feature files and the underlying Ruby code of your Rails application.</p>

<p>Typically you will be using Cucumber in conjunction with Webrat to test your application. Webrat acts as the person behind the keyboard clicking around the site, filling out forms and viewing resulting pages. If you&#8217;ve ever tested your project by manually filling out forms and verifying output, that&#8217;s exactly what Webrat does for you, except it&#8217;s automated.</p>

<h4>Let&#8217;s Get Testing Already</h4>

<p>Rather than go into detail about <a href="http://en.wikipedia.org/wiki/Test-driven_development"><span class="caps">TDD</span></a> or <a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development"><span class="caps">BDD</span></a> and why you should use them, I&#8217;m going to assume that you&#8217;re like most Rails developers looking to learn more about testing. You probably have an application or two out there in the wild, seemingly working just fine. However, you know that you should get some test coverage in there so that you can confidently make changes and debug problems as they come up. With that in mind, I am going to use a sample application that already has some functionality and we will add our Cucumber tests where needed.</p>

<h4>A Veterinary Patient Management System</h4>

<p>Our sample application is a simple patient management system for a Veterinarian that deals with Owners, Pets and Visitations. Let&#8217;s take a look at some of the models.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;">&nbsp;
    <span style="color:#9966CC; font-weight:bold;">class</span> Owner <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
&nbsp;
      has_many <span style="color:#ff3333; font-weight:bold;">:pets</span>
      validates_presence_of <span style="color:#ff3333; font-weight:bold;">:name</span>
      validates_presence_of <span style="color:#ff3333; font-weight:bold;">:email</span>
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">class</span> Pet <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
      belongs_to <span style="color:#ff3333; font-weight:bold;">:owner</span>
&nbsp;
      validates_presence_of  <span style="color:#ff3333; font-weight:bold;">:name</span>
      validates_presence_of  <span style="color:#ff3333; font-weight:bold;">:species</span>
      validates_inclusion_of <span style="color:#ff3333; font-weight:bold;">:species</span>, :<span style="color:#9966CC; font-weight:bold;">in</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">%</span>w<span style="color:#006600; font-weight:bold;">&#40;</span> dog cat bird snake <span style="color:#006600; font-weight:bold;">&#41;</span>,
      <span style="color:#ff3333; font-weight:bold;">:message</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;Species: %s is not included in the list of accepted species&quot;</span>
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">class</span> Visitation <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
&nbsp;
      has_one <span style="color:#ff3333; font-weight:bold;">:pet</span>
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>




<p>The first thing for which we&#8217;ll be adding a Feature is the process for creating a new Owner record. When a new client calls the Veterinarian&#8217;s office, an employee needs to enter them into the system.</p>

<h4>Writing a Feature</h4>

<p>Cucumber features are very straight forward. The feature file explains a set of functionality by describing different cases through scenarios.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="" style="font-family:monospace;">&nbsp;
    Feature: Manage Owners
      In order to value
      As a role
      I want feature
&nbsp;
      Scenario: title
        Given context
        When event
        Then outcome</pre></td></tr></table></div>




<p>Each Cucumber feature represents a desired software feature that a certain user of the system wants in order to achieve some end goal.  The scenarios are formatted so that a context is setup, an event occurs and an outcome is evaluated.</p>

<p>Let&#8217;s examine our real <code>Manage Owners</code> feature.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="" style="font-family:monospace;">&nbsp;
    Feature: Managing Owners
      In order to manage our client list
      As an employee
      I want to be able to CRUD owners
&nbsp;
      Scenario: Creating a new Owner
        Given I am on the homepage
        And I follow &quot;Owners&quot;
        Then I should be on the owners index page
        Given I follow &quot;New owner&quot;
        And I fill in &quot;Name&quot; with &quot;Clayton&quot;
        And I fill in &quot;E-Mail&quot; with &quot;clayton@example.org&quot;
        And I fill in &quot;Address&quot; with &quot;<span style="">100</span> Cactus Rd&quot;
        And I fill in &quot;City&quot; with &quot;Scottsdale&quot;
        And I fill in &quot;State&quot; with &quot;Arizona&quot;
        And I fill in &quot;Postal Code&quot; with &quot;<span style="">85000</span>&quot;
        And I fill in &quot;Phone&quot; with &quot;<span style="">480</span>-<span style="">555</span>-<span style="">1212</span>&quot;
        When I press &quot;Create&quot;
        Then I should see &quot;Owner was successfully created.&quot;
        And I should be on the owners index page</pre></td></tr></table></div>




<p class="note">Note: When you specify &#8220;And&#8221; in a Cucumber feature the step inherits the Given/Then/When from the previous step</p>

<p>Our scenario covers the act of creating a new Owner record. We first setup a context (I am on the homepage). Next we click a link in the navigation (I follow &#8220;Owners&#8221;). Once we&#8217;re on the <code>index</code> view for the Owners controller (I should be on) we can click another link to get to the <code>new</code> view for the Owners controller. From there we are simply instructing Webrat to fill out our form (I fill in) and click the submit button at the bottom (I press &#8220;Create&#8221;). Finally we are asking Webrat to read the resulting page and see if there is some text present (I should see).</p>

<p>Our feature is looking pretty good, but we still have a few more steps before we can get this scenario passing. Running the this feature from the command line will give us some output and more direction. Once you&#8217;re run <code>rake db:migrate</code> and <code>rake db:test:prepare</code> run the following from your application&#8217;s root directory:</p>



<pre>

  ruby cucumber features/manage_owners.feature

</pre>



<p>Looks like we&#8217;re failing, and Cucumber gave us some information about what&#8217;s wrong.</p>



<pre>

  Can't find mapping from &quot;the owners index page&quot; to a path.
  Now, go and add a mapping in patient-management/features/support/paths.rb

</pre>



<p>If we open up our <code>features/support/paths.rb</code> file we can add the correct path right below the default path for the &#8220;home page&#8221;. The paths file is really just a list of regular expressions that Cucumber uses to match named routes to words in scenarios.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="" style="font-family:monospace;">&nbsp;
  when /the homes?page/
    '/'
  when /the owners index page/
    owners_path</pre></td></tr></table></div>




<p>With that little change we have our first passing Cucumber scenario! When running Cucumber features from the command line, Cucumber will print out a little summary message.</p>



<pre>

    1 scenario (1 passed)
    14 steps (14 passed)
    0m0.290s

</pre>



<h4>Complex Scenario Setup</h4>

<p>In our above example the setup, or Given steps, were pretty simple. However, sometimes you need more complex setups for your scenarios, like editing a record for example. Cucumber makes it easy to create objects in your scenarios using tables in <a href="http://wiki.github.com/aslakhellesoy/cucumber/multiline-step-arguments">multiline step arguments</a>.</p>

<p>Here is a feature that goes through the process of editing an owner&#8217;s address. You&#8217;ll see the Cucumber table that is used to setup our existing owner record. The first row in the Cucumber table correspond to some of the attribute names for our Owner model.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="" style="font-family:monospace;">    Scenario: Editing an existing Owner
      Given the following owners:
       | name    | email               | address       |
       | Clayton | clayton@example.org | <span style="">100</span> Cactus Rd |
      Given I am on the homepage
      And I follow &quot;Owners&quot;
      Then I should be on the owners index page
      When I follow &quot;Edit&quot;
      And I fill in &quot;Address&quot; with &quot;<span style="">567</span> N Scottsdale Rd&quot;
      When I press &quot;Update&quot;
      Then I should see &quot;Owner was successfully updated.&quot;
      And I should be on the owners index page</pre></td></tr></table></div>




<p>When we try to run this, Cucumber will give us the &#8220;shell&#8221; for our custom step definition &#8220;Given the following owners&#8221;.</p>



<pre>
    Given /^the following owners:$/ do |table|
      # table is a Cucumber::Ast::Table
      pending # express the regexp above with the code you wish you had
    end
</pre>



<p>Since we never created a step definition for this Cucumber feature, we can go ahead and add a new file, <code>features/step_definitions/manage_owners_steps.rb</code>. It is important to note that Cucumber will load all of the files in <code>features/step_definitions</code> and that steps can be used across scenarios and features. If you think you&#8217;re going to re-use a step definition, it might be a good idea to place it in something like <code>features/step_definitions/shared_steps.rb</code>.</p>

<p class="note">Note: You should put some thought into your <a href="http://wiki.github.com/aslakhellesoy/cucumber/step-organisation">step organization</a> as your project grows in size.</p>

<p>Cucumber takes the table argument from your scenario and turns it into an array of hashes, which is technically a <code>Cucumber::Ast::Table</code> object. By iterating through each hash of the array, we can build up an object that we can use later in our tests. Since we want this object to live in the database and we don&#8217;t want to describe every attribute of the owner in our scenario, we can use Factory Girl to simplify the process.</p>

<p>The factory for our owner is simple. I won&#8217;t go into the specifics of how to create factories as that&#8217;s a whole other article. You can read more about using factories on the <a href="http://github.com/thoughtbot/factory_girl">github project page</a></p>

<p>Create a file to store your factories in <code>features/support/factories.rb</code> and copy the following.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;">    <span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'factory_girl'</span>
&nbsp;
    Factory.<span style="color:#9900CC;">define</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:owner</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>o<span style="color:#006600; font-weight:bold;">|</span>
      o.<span style="color:#9900CC;">name</span> <span style="color:#996600;">&quot;John Doe&quot;</span>
      o.<span style="color:#9900CC;">email</span> <span style="color:#996600;">&quot;john@example.org&quot;</span>
      o.<span style="color:#9900CC;">address</span> <span style="color:#996600;">&quot;123 Elm Street&quot;</span>
      o.<span style="color:#9900CC;">city</span> <span style="color:#996600;">&quot;Phoenix&quot;</span>
      o.<span style="color:#9900CC;">state</span> <span style="color:#996600;">&quot;Arizona&quot;</span>
      o.<span style="color:#9900CC;">zip</span> <span style="color:#996600;">&quot;85000&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>




<p>When we use the factory to create our object, Factory Girl will take the attribute hash that we&#8217;ve passed in when creating the object and use those values for the object. Factory Girl will also fill in any blank attributes with the defaults we&#8217;ve specified in the factory definition. The record that is created will actually exist in the database, it is not a mock and it does not have any stubs, as far as our Rails app is concerned it is just a regular record in the database.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;">    Given <span style="color:#006600; font-weight:bold;">/</span>^the following owners:$<span style="color:#006600; font-weight:bold;">/</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>table<span style="color:#006600; font-weight:bold;">|</span>
      table.<span style="color:#9900CC;">hashes</span>.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>attributes<span style="color:#006600; font-weight:bold;">|</span>
        <span style="color:#008000; font-style:italic;"># {:name =&gt; &quot;Clayton&quot;, :email =&gt; &quot;clayton@example.org&quot;, </span>
        <span style="color:#ff3333; font-weight:bold;">:address</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;100 Cactus Rd&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
        Factory.<span style="color:#9900CC;">create</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:owner</span>, attributes<span style="color:#006600; font-weight:bold;">&#41;</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>




<p>Another place we could use our <code>Given the following owners</code> step would be when creating a feature that deals with creating Pet records. An owner <code>has_many</code> pets while a pet <code>belongs_to</code> an owner. When we create a pet record, we need an existing owner record to which we&#8217;ll link the pet record. Start by creating a new feature file, <code>features/manage_pets.feature</code>.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="" style="font-family:monospace;">    Scenario: Creating a pet
      Given the following owners:
       | name    | email               |
       | Clayton | clayton@example.org |
      Given I am on the homepage
      And I follow &quot;Pets&quot;
      And I follow &quot;New pet&quot;
      When I fill in &quot;Name&quot; with &quot;Bruno&quot;
      And I select &quot;Dog&quot; from &quot;Species&quot;
      And I select &quot;March 19th, <span style="">2005</span>&quot; as the &quot;DOB&quot; date
      And I select &quot;Clayton <span class="br0">&#40;</span>clayton@example.org<span class="br0">&#41;</span>&quot; from &quot;Owner&quot;
      When I press &quot;Create&quot;
      Then I should see &quot;Bruno was successfully created.&quot;
      And I should be on the pets index page
      And a pet named &quot;Bruno&quot; should be owned by an owner named &quot;Clayton&quot;</pre></td></tr></table></div>




<p>In this example we have re-used our <code>Given the following owners</code> table. We have also made use of some new Webrat steps like <code>I select</code> for interacting with select lists and <code>I select [DATE] as the [DATE LABEL] date</code> for selecting a date from Rails&#8217; <code>date_selector</code> helper. Finally, there is a custom step that we are going to use to make sure that the connection between our newly created pet and the existing owner is in place.</p>

<p>Let&#8217;s take a look at the step definition for our custom step above.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;">&nbsp;
    <span style="color:#9966CC; font-weight:bold;">Then</span> <span style="color:#006600; font-weight:bold;">/</span>^a pet named <span style="color:#996600;">&quot;([^&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">*</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#996600;">&quot; should be owned by an owner named &quot;</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#91;</span>^<span style="color:#996600;">&quot;]*)&quot;</span>$<span style="color:#006600; font-weight:bold;">/</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>pet_name, owner_name<span style="color:#006600; font-weight:bold;">|</span>
      Pet.<span style="color:#9900CC;">find_by_name</span><span style="color:#006600; font-weight:bold;">&#40;</span>pet_name<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">owner</span>.<span style="color:#9900CC;">name</span>.<span style="color:#9900CC;">should</span> == owner_name
    <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>




<p>When you place something in double quotes in your scenario steps, like &#8220;Bruno&#8221; and &#8220;Clayton&#8221; in our example, they are captured using regular expressions in the step definition. Cucumber then passes the matched values along so that then can be used in your assertion. We can find the pet based on the <code>pet_name</code> and make sure that the <code>owner</code> linked to this pet via the <code>belongs_to</code> association is the same as the <code>owner_name</code> we specified in our scenario. This is an example of how Cucumber can be used, with RSpec matchers, to make an assertion that has nothing to do with inspecting the <span class="caps">DOM </span>of a resulting webpage.</p>

<p class="note">Note: Beware of the <a href="http://wiki.github.com/aslakhellesoy/cucumber/conjunction-steps-antipattern">Conjunction Steps</a> Anti-pattern</p>

<h4>Scenario Outlines</h4>

<p>Cucumber provides a very simple way to test multiple different situations with a single scenario. These might be edge cases or just repetitive examples that don&#8217;t require their own scenario.</p>

<p>We have some business logic in our application that determines when an appointment, or <code>Visitation</code>, can be made with the Veterinarian:</p>


<ul>
<li>Visitations less than three days from today require approval before being booked</li>
<li>No visitations can be booked more than six months in advance</li>
<li>No visitations can be booked in the past</li>
</ul>



<p>We can easily represent this using a Cucumber <a href="http://wiki.github.com/aslakhellesoy/cucumber/scenario-outlines">Scenario Outline</a>. Start by creating a new feature <code>features/visitation_logic.feature</code>. Also, because we&#8217;re going to be working with time and date specific business logic, this is a good time to point out that we can stub methods when using Cucumber, however, this practice is frowned upon and should only be used for things like dates and connecting to external <span class="caps">API</span>s.</p>

<p>To add stubbing support add the following to your <code>features/support/custom_env.rb</code> file.</p>



<pre>
  require 'spec/stubs/cucumber'
</pre>




<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="" style="font-family:monospace;">&nbsp;
    Scenario Outline: visitations
      Given the following owners:
        | name    |
        | Clayton |
      And the following pets:
        | name  |
        | Bruno |
      Given today is &quot;&lt;today&gt;&quot;
      Given I am on the home page
      And I follow &quot;Visitations&quot;
      And I follow &quot;New visitation&quot;
      And I select &quot;Bruno <span class="br0">&#40;</span>Owned by Clayton<span class="br0">&#41;</span>&quot; from &quot;Pet&quot;
      And I select &quot;&lt;date&gt;&quot; as the &quot;Appointment Date&quot; date
      When I press &quot;Create&quot;
      Then I should see &quot;&lt;message&gt;&quot;
&nbsp;
    Examples:
      | today      | date               | message                                           |
      | <span style="">2010</span>-01-01 | January 2nd, <span style="">2010</span>  | Visitation requires short notice approval.        |
      | <span style="">2010</span>-01-01 | January 31st, <span style="">2010</span> | Visitation succesfully created.                   |
      | <span style="">2010</span>-01-01 | November 2nd, <span style="">2010</span> | Visitations cannot be booked that far in advance. |
      | <span style="">2010</span>-04-01 | January 2nd, <span style="">2010</span>  | Visitations cannot be booked in the past.         |</pre></td></tr></table></div>




<p>Cucumber will go through the <code>Scenario Outline</code> you have created and substitute the values in &lt;&gt;&#8217;s with their corresponding value in the <code>Examples</code> table at the bottom. Cucumber goes through each line in the <code>Examples</code> table and runs the scenario using your specified values.</p>


<p>First, lets implement the step for stubbing our today&#8217;s date.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="" style="font-family:monospace;">&nbsp;
    Given /^today is &quot;<span class="br0">&#40;</span><span class="br0">&#91;</span>^&quot;<span class="br0">&#93;</span>*<span class="br0">&#41;</span>&quot;$/ do |date|
      Date.stub<span class="br0">&#40;</span>:today<span class="br0">&#41;</span>.and_return<span class="br0">&#40;</span>Date.parse<span class="br0">&#40;</span>date<span class="br0">&#41;</span><span class="br0">&#41;</span>
    end</pre></td></tr></table></div>




<p>In <code>features/step_definitions/shared_steps.rb</code> we can add the implementation for <code>Given the following pets</code>. We are cheating here because we&#8217;re not explicitly linking the Pet to the Owner in our scenario outline. This example isn&#8217;t so bad, but keep in mind that this association is not obvious when reading the scenario. This type of &#8220;behind the scenes&#8221; scenario setup is generally a bad idea as it obscures what&#8217;s really happening. Since we&#8217;ve already created the owner we can just find the first one in the database and create the pet records using the appropriate Rails&#8217; association method.</p>



<pre>

    Given /^the following pets:$/ do |table|
      table.hashes.each do |attributes|
        Owner.first.pets.create(attributes)
      end
    end

</pre>



<p>The other steps in our scenario already exist, either because we created them, or because they come for free with the built in steps. In this one scenario we were able to test four different business logic outcomes. This test could be expanded to go beyond what is shown on the resulting page, perhaps to ensure that an Approval record was created for the short-notice appointment.</p>

<h4>Advanced Cucumber Goodies</h4>

<p>While you should now have an understanding of the basics of Cucumber, there are a number of other powerful features.</p>

<p><strong>Tags</strong></p>

<p>Cucumber allows you to &#8220;tag&#8221; your scenarios and features so that they can be run, not run or have special other tasks run before and after them. Out of the box you get the <code>@wip</code> tag (Work In Progress) which isn&#8217;t run as part of the normal <code>rake cucumber:ok</code> process.</p>

<p><strong>Hooks</strong></p>

<p>Using tags, you can run <code>Before</code> and <code>After</code> tasks that run some code before or after a given feature or scenario. You can even run these hooks before or after all of your features. You might need to do some cleanup of generated files in an After hook or some <span class="caps">CPU </span>expensive operation before a single scenario that you don&#8217;t want running before all of your scenarios.</p>

<p><strong>Table Transformations</strong></p>

<p>The tables that we have been creating use the exact model attribute names for their header rows. This is convenient for the developer, but makes the scenarios harder to understand. This is especially true if you have very strange or legacy attribute names like <code>record_quote_ext_type__c</code>. Using table transformations you can use &#8220;Record Extension Type&#8221; in your scenario table and map that to <code>record_quote_ext_type__c</code> in your step definition.</p>

<p><strong>Calling Steps from Steps</strong></p>

<p>It&#8217;s possible to take a multi-step process, expressed in Cucumber steps, and call them all at once from another step. You might have a few steps that describe logging in to a system (filling out login credentials, pressing a button etc.) You can easily put them all into one step, <code>Given I am logged in</code>, and then reference that elsewhere. This helps to reduce unnecessary repetition of steps and keep your scenarios to a manageable size.</p>

<p><strong>Profiles</strong></p>

<p>Cucumber allows you to specify a profile to use when running your features. By default Cucumber will not run any <code>@wip</code> tagged scenarios and the output will contain any failing files and the line number of the failure. However, if you wanted to run the <code>@production</code> tagged stories and output a nice <span class="caps">HTML </span>report, you could setup a new profile for that in <code>config/cucumber.yml</code> and use it when running your features.</p>

<p><strong>Testing Javascript</strong></p>

<p>You can even use Cucumber to test complex javascript. Tools like <a href="http://celerity.rubyforge.org/">Celerity</a> with <a href="http://github.com/langalex/culerity">Culerity</a> or <a href="http://seleniumhq.org/">Selenium</a> give you the ability go beyond the interactions provided by Webrat. A new addition to Cucumber is <a href="http://github.com/jnicklas/capybara">Capybara</a> support which aims to unify the language used in steps so that you can use Webrat, Selenium and Celerity side-by-side.</p>]]></content:encoded>
			<wfw:commentRss>http://www.claytonlz.com/2010/03/zero-to-tested-with-cucumber-and-factory-girl/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Use Cucumber Table Transformations To Build Objects</title>
		<link>http://www.claytonlz.com/2010/01/cucumber-table-transformations/</link>
		<comments>http://www.claytonlz.com/2010/01/cucumber-table-transformations/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 17:30:02 +0000</pubDate>
		<dc:creator>Clayton</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Ruby On Rails]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[cucumber testing rails guide]]></category>

		<guid isPermaLink="false">http://www.claytonlz.com/?p=397</guid>
		<description><![CDATA[
