
<?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>Cory Schires &#187; Best-Practices</title>
	<atom:link href="http://coryschires.com/tag/best-practices/feed/" rel="self" type="application/rss+xml" />
	<link>http://coryschires.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Sun, 01 Jan 2012 23:49:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Ten tips for writing better Cucumber steps</title>
		<link>http://coryschires.com/ten-tips-for-writing-better-cucumber-steps/</link>
		<comments>http://coryschires.com/ten-tips-for-writing-better-cucumber-steps/#comments</comments>
		<pubDate>Sun, 01 Jan 2012 23:08:19 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[Best-Practices]]></category>
		<category><![CDATA[Capybara]]></category>
		<category><![CDATA[Cucumber]]></category>
		<category><![CDATA[Ruby-on-Rails]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=420</guid>
		<description><![CDATA[I've written hundreds of Cucumber steps. Here's some tips I learned along the way.]]></description>
			<content:encoded><![CDATA[<h3>1. Use flexible pluralization.</h3>
<p>Add a <span class="code_text">?</span> immediately following the pluralized word:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^the users? should receive an email$/ do
          # ...
        end
    </pre>
</div>
<p>The <span class="code_text">?</span> specifies that your looking for zero or more of the proceeding character. So the above example will capture both <span class="code_text">user</span> and <span class="code_text">users</span>.</p>
<h3>2. Use non-capturing groups to help steps read naturally.</h3>
<p>You can create non-capturing groups by adding a <span class="code_text">?:</span> to the beginning of a otherwise normal group (e.g. <span class="code_text">(?:some text)</span> rather than <span class="code_text">(some text)</span>). This is treated exactly like a normal group except that the result will is not captured and thus not passed as an argument to your step definition. This often useful in conjunction with alternation:</p>
<div class="code_block">
<pre class="brush: ruby;">
        And /^once the files? (?:have|has) finished processing$/ do
          # ...
        end
    </pre>
</div>
<p>Or another pattern I use regularly:</p>
<div class="code_block">
<pre class="brush: ruby;">
        When /^(?:I|they) create a profile$/ do
          # ...
        end
    </pre>
</div>
<h3>3. Consolidate step definitions by capturing optional groups.</h3>
<p>Often I find myself writing essentially the same step with both positive and negative assertions. You can remove this duplication by capturing an optional group:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^I should( not)? see the following columns: "([^"]*)"$/ do |negate, columns|
          within('table thead tr') do
            columns.split(', ').each do |column|
              negate ? page.should_not(have_content(column)) : page.should(have_content(column))
            end
          end
        end
    </pre>
</div>
<p>Here we&#8217;re capturing an optional group (note <span class="code_text">( not)?</span> using the <span class="code_text">?</span> mentioned above). We then pass that into our step as the <span class="code_text">negate</span> variable which we can use to write conditional assertions.</p>
<h3>4. Not all matched phrases need to be surrounded by quotes.</h3>
<p>Don&#8217;t assume that matched phrases must (or should) be enclosed in double quotes. Often quotes are a good idea. They makes it visually clear which phrases will be passed to the step definition. For example:</p>
<div class="code_block">
<pre class="brush: plain;">
        Given I have "potatoes" in my cart
    </pre>
</div>
<p>That&#8217;s reasonable. The quotes highlight the parts that change without hurting readability. But sometimes, quotes are just poor style:</p>
<div class="code_block">
<pre class="brush: plain;">
        Given I have "7" items in my cart
    </pre>
</div>
<p>It should be pretty obvious that the number is variable. The quotes add nothing except noise. A better step would read:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^I have (\d+) items? in my cart$/ do |item_count|
          item_count.to_i.times { ... }
        end
    </pre>
</div>
<h3>5. Use transforms to make smarter, DRYer regular expressions.</h3>
<p>There&#8217;s an opportunity to refactor the previous example. Do you see it? Cucumber passes everything as a string, so you must remember to convert types within your step definition (e.g. above we use <span class="code_text">to_i</span> to transform <span class="code_text">item_count</span> into a proper integer). That&#8217;s annoying and easy to forget.</p>
<p>Fortunately, Cucumber gives us a way to avoid this peskiness by using <span class="code_text">Transform</span>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        CAPTURE_A_NUMBER = Transform /^\d+$/ do |number|
          number.to_i
        end
    </pre>
</div>
<p>And we can use this in our steps:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^I have (#{CAPTURE_A_NUMBER}) items? in my cart$/ do |item_count|
          item_count.times { ... }
        end
    </pre>
</div>
<p>Not only have we removed the need to call <span class="code_text">to_i</span> but we&#8217;ve also moved our regex into a reusable constant.</p>
<h3>6. Define methods to DRY up your step definitions.</h3>
<p>Sometimes it&#8217;s a good idea to remove duplication by defining methods. For example, it&#8217;s common to define a <span class="code_text">current_user</span> method:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def current_user
          User.find_by_email('current_user@example.com')
        end
    </pre>
</div>
<p>Similarly, if you find yourself wrapping several steps with the same logic, you might consider making a helper method. On <a href="http://scholasticahq.com/">Scholastica</a>, we test a lot of lightboxes using of this method:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def within_lightbox(opts = {sleep: 0} )
          sleep(opts[:sleep])
          within_frame("prettyPhotoIframe") { yield }
        end
    </pre>
</div>
<p>And our step definitions stay nice and clean:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^some stuff should be visible in the lightbox$/ do
          within_lightbox { page.should have_content('Some Stuff') }
        end
    </pre>
</div>
<p>By convention, these methods should live in <span class="code_text">features/support/world_extensions.rb</span> and be included in the Cucumber <span class="code_text">World</span> module. But keep in mind this is a tradeoff: you&#8217;re removing duplication but adding indirection. You should be reluctant to define methods until the code makes it very obvious that it&#8217;s a good idea.</p>
<h3>7. Use steps within steps.</h3>
<p>Sometimes it&#8217;s useful to call steps within steps. Another example from <a href="scholasticahq.com">Scholastica</a>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        When /^the request for an expedited decision should be canceled$/ do
          manuscript.should_not be_expedited
          step %{"#{current_user.email}" should receive an email with subject "Expedited decision request canceled"}
        end
    </pre>
</div>
<p>But don&#8217;t go crazy, it&#8217;s better to use the capybara methods directly when possible:</p>
<div class="code_block">
<pre class="brush: ruby;">
        When /^I update the email template to read "([^"]*)"$/ do |text|
          fill_in("email_template[text], with: text)
          click_button("Save changes and close")
          # Rather than...
          # step %{I fill in "email_template[text]" with "#{text}"}
          # step %{I press "Save changes and close"}
        end
    </pre>
</div>
<h3>8. Improve readability with unanchored regular expressions.</h3>
<p>Most step definitions look something like:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Given /^I am an admin user$/ do |item_count|
          # ...
        end
    </pre>
</div>
<p>Note we&#8217;re using <span class="code_text">^</span> and <span class="code_text">$</span> to anchor our regex to the start and end of the captured string. This ensures the regular expression exactly matches &#8220;I am an admin user&#8221; (i.e. allows no additional words at the beginning or end of the step). Most of the time, this is exactly what want.</p>
<p>Occasionally, however, it makes sense to omit the final <span class="code_text">$</span>. Take this step for example:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^wait (\d+) seconds/ do |seconds|
          sleep(seconds.to_i)
        end
    </pre>
</div>
<p>Now you can use this definition to write flexible, expressive steps:</p>
<div class="code_block">
<pre class="brush: plain;">
        Then wait 2 seconds for the revenue statistics to finish loading
        Then wait 5 seconds while the document is converted
    </pre>
</div>
<h3>9. When your steps must include data, use tables.</h3>
<p>Generally, steps should be human readable and that means they shouldn&#8217;t include loads of cryptic data. But sometimes, you have no other choice. In those cases, use tables to clearly represent the data:</p>
<div class="code_block">
<pre class="brush: plain;">
        Given "Frankie's Hams" are selling for $25:
        And the following orders have been placed:
          | buyer email      | quantity |
          | eddy@example.com | 3        |
          | matt@example.com | 2        |
    </pre>
</div>
<p>Using tables within your step definitions can get a bit tricky. I use <a href="https://gist.github.com/1548498">this helper method</a> but you should really <a href="https://github.com/cucumber/cucumber/blob/master/lib/cucumber/ast/table.rb">read the relevant source code</a> and figure out what makes sense for your application.</p>
<h3>10. Don&#8217;t get carried away and spoil a good thing.</h3>
<p>As you use these tips, remember that tests should favor clarity over cleverness. In other words, if you&#8217;re removing a small amount of duplication but adding a lot of complexity, that&#8217;s a poor tradeoff. Here&#8217;s an example from <a href="scholasticahq.com">Scholastica</a>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Given /^(?:I|they) have opened (?:a|an) ([^\s]+) invitation$/ do |invitation_type|
          invitation = Factory("#{invitation_type}_invitation".to_sym, recipient: current_user, to: current_user.email)
          reset_mailer
          eval "ApplicationMailer.invite_#{invitation_type}(invitation).deliver"
          open_email(current_user.email)
        end
    </pre>
</div>
<p>This steps allows us to write both <span class="code_text">Given I have opened a reviewer invitation</span> and <span class="code_text">Given I have opened an editor invitation</span>. I&#8217;d say this step is borderline too complex (lots of interpolation and an eval). Maybe it would be better to just write two separate steps? Remember no one is testing your tests so don&#8217;t fuck around. A little bit of duplication is not the end of the world.</p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/ten-tips-for-writing-better-cucumber-steps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maintaining a reading list on GitHub</title>
		<link>http://coryschires.com/maintaining-a-reading-list-on-github/</link>
		<comments>http://coryschires.com/maintaining-a-reading-list-on-github/#comments</comments>
		<pubDate>Mon, 21 Feb 2011 21:45:16 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Best-Practices]]></category>
		<category><![CDATA[GitHub]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=382</guid>
		<description><![CDATA[Recently I took the time to post a reading list to GitHub. I've found some surprising benefits...]]></description>
			<content:encoded><![CDATA[<p>Like any decent programmer, I spend a lot of time reading. For the most part it runs in cycles: read a bunch of stuff, apply what you&#8217;ve learned, read a bunch more, and so on. This is a pretty typical pattern as becoming a strong developer requires a good mix of learning and doing. So, inspired in part by <a href="http://oreilly.com/catalog/9780596518387" class="new_window">Apprenticeship Patterns</a>, I&#8217;ve decided to start maintaining a reading list.</p>
<p><img class="blog_post_banner" src="http://coryschires-blog-post-images.s3.amazonaws.com/reading-list.png" alt="Screenshot of reading list"></p>
<h3>Some simple ground rules for myself.</h3>
<ul>
<li>List should be <a href="https://github.com/coryschires/reading-list" class="new_window">publicly available on github</a>.</li>
<li>Be honest about what books I’ve read, partially read, and plan to read.</li>
<li>Write a few sentences about each book &ndash; mostly for myself but also for anyone who might be interested.</li>
<li>Only include books related to development, user experience design, and entrepreneurship.</li>
<li>Include screencasts as well since that’s how I do much of my learning.</li>
</ul>
<h3>I&#8217;ve already noticed some benefits.</h3>
<p>Although it&#8217;s only been a short time, I can already attest to the usefulness of keeping track of what you&#8217;ve read. Just building the list requires going back through all the stuff you&#8217;ve read and watched over the past few years. It&#8217;ll get you thinking about how you learn, including some really interesting questions:</p>
<ul>
<li>How have your interests moved between topics?</li>
<li>What topics do you keep coming back to?</li>
<li>What periods were most productive?</li>
<li>What topics required a few books before you really understood?</li>
<li>What type of books are most useful for the way you learn? (e.g. Do you learn better with lots of examples or would you rather read a short book twice?)</li>
<li>Were any of the books disappointing? Why?</li>
</ul>
<p>I think it&#8217;s important that your list be more than a catalogue of titles and author names. You should take the time to reflect on why the book mattered (i.e. what did you take away from the read?). While this means writing a few sentences for each entry, don&#8217;t get too fixated. There&#8217;s no reason to write a summary or book review. The writeup is just to get you thinking broadly about the book.</p>
<h3>And you should do it too.</h3>
<p>Finally, I&#8217;d like to see other developers maintaining a reading list &ndash; specifically on GitHub. It&#8217;d be awesome if I could look up serious developers to check out what they&#8217;re reading and, more importantly, what they recommend. It&#8217;d be a nice adjunct to reading their code.</p>
<p><a href="https://github.com/coryschires/reading-list" class="download">View my reading list on Github</a></p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/maintaining-a-reading-list-on-github/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Why you should deeply nest your CSS selectors.</title>
		<link>http://coryschires.com/why-you-should-deeply-nest-your-css-selectors/</link>
		<comments>http://coryschires.com/why-you-should-deeply-nest-your-css-selectors/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 02:43:37 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Best-Practices]]></category>
		<category><![CDATA[CSS]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=276</guid>
		<description><![CDATA[Most developers, even experienced developers, don't understand the value of deeply nesting CSS selectors...Your code will be better organized, easier to read, and more maintainable....]]></description>
			<content:encoded><![CDATA[<p>Most developers, even experienced developers, don&#8217;t understand the value of deeply nesting CSS selectors. Although writing the same selectors over and over might seem redundant, it&#8217;s worth the extra effort. Your code will be better organized, easier to read, and more maintainable. </p>
<h3>What do you mean by deeply nested selectors?</h3>
<p>Most of us learn to write CSS using shallow selectors. Essentially, you give an element a hook (class or id) and use it to write some style:</p>
<div class="code_block">
<pre class="brush: css;">
        #our_team { height: 230px; margin: 60px 0 0 0; }
        .employee { float: left; margin: 0 0 0 10px; }
        .name { text-decoration: underline; }
        .position { color: #add036; font-size: 10px; }
    </pre>
</div>
<p>But you can also trace each selector back to its common ancestor element:</p>
<div class="code_block">
<pre class="brush: css;">
        #our_team { height: 230px; margin: 60px 0 0 0; }
        #our_team .employee { width: 230px; height: 65px; float: left; }
        #our_team .employee a img { float: left; border: thin solid #5F6568; }
        #our_team .employee p { float: left; margin: 0 0 0 10px;  }
        #our_team .employee p span { display: block; margin: 0; }
        #our_team .employee p a span.name { line-height: 16px; font-size: 14px; }
        #our_team .employee p a:hover span.name { text-decoration: underline; }
        #our_team .employee p span.position { color: #add036; font-size: 10px; }
    </pre>
</div>
<h3>And why is this better?</h3>
<h4><span>1</span> It&#8217;s easy to quickly trace a given selector back to its parent element.</h4>
<p>In the above example, we know at a glance that <span class="code_text">.position</span> refers to an employee&#8217;s position and not something else (e.g. a utility class that adjusts an element&#8217;s position). This keeps things more explicit and thus less confusing.</p>
<h4><span>2</span> It divides your code into distinctive visual blocks.</h4>
<p>Take the above example, not only can you quickly identify all the selectors that belong to <span class="code_text">#our_team</span> but you can also see how the style cascades through the element. This is especially useful when your stylesheet grows past a few hundred lines.</p>
<h4><span>3</span> Your rules won&#8217;t inadvertently override each other.</h4>
<p>Because all selectors trace back to a unique ancestor element, you can be sure that everything nested within that selector will only effect its intended target. This means you can use common class names (e.g. <span class="code_text">.first</span>, <span class="code_text">.title</span>, <span class="code_text">.column</span>, etc.) with confidence that you won&#8217;t be breaking the styling elsewhere on your site.</p>
<h4><span>4</span> You get the benefits of cascading without the headaches.</h4>
<p>When using shallow selectors, you often rely on the order that selectors appear in your stylesheet. For example, if you have two selectors of the same value, priority will be given to whichever selector appears last in your stylesheet. That&#8217;s fine except when rules start cascading in unintended ways. Then rules become unresponsive because some other selector, four hundred lines lower, is running the show. </p>
<p>But deeply nested selectors don&#8217;t have this problem. Because everything traces back to a unique selector, you can be sure your rules will stick <span class="italic">no matter where they appear in the stylesheet</span>. And, of course, you can still enjoy the benefits of cascading within the scope of a unique ancestor.</p>
<h4><span>5</span> You can safely use @import to organize your stylesheets.</h4>
<p>Stylesheets can get really long and most of us have devised clever means of trying to keep things organized (e.g. headers, sub-sections, comments, etc.). But the best strategy is to divide your stylesheet into logical chunks, save those chunks as separate files, and include everything (as needed) into a few master stylesheets using the <span class="code_text">@import</span> directive. This is easier on your server (since you&#8217;re only linking to a few stylesheets) and on your brain (since you&#8217;re not scanning through a stylesheet that&#8217;s 3000 lines long).</p>
<p>But this strategy is problematic since all <span class="code_text">@import</span> directives must be placed at the very top of your stylesheet. And, because the normal rules of cascading still apply, you can run into inheritance problems pretty quickly if you try to do something like this: </p>
<div class="code_block">
<pre class="brush: css;">
        @import url("reset.css");
        @import url("header.css");
        @import url("footer.css");

        /* ...a bunch of selectors that will likely over-
        ride what you're trying to do in footer.css... */
    </pre>
</div>
<p>But if your selectors are deeply nested you can use <span class="code_text">@import</span> with impunity. So long as your selectors trace back to a unique ancestor the order of inclusion makes no difference. You can import <span class="code_text">footer.css</span> before <span class="code_text">reset.css</span> and it&#8217;s not going to do any harm.</p>
<p>This means you can use <span class="code_text">@import</span> the way would a php <span class="code_text">include()</span> statement or a rails <span class="code_text">:partial</span> in a template. In other words, you can really break things up and keep your stylesheets super organized:</p>
<div class="code_block">
<pre class="brush: css;">
        @import url("reset.css");
        @import url("utilities.css");
        @import url("typography.css");
        @import url("page_structure.css");
        @import url("header.css");
        @import url("main_nav.css");
        @import url("footer.css");

        /* ...the specific style for each individual page
        with all the shared styles neatly partitioned into
        separate files... */
    </pre>
</div>
<p>Hope this helps get those stylesheets under control.</p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/why-you-should-deeply-nest-your-css-selectors/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>A lesson in not repeating yourself.</title>
		<link>http://coryschires.com/a-lesson-in-not-repeating-yourself/</link>
		<comments>http://coryschires.com/a-lesson-in-not-repeating-yourself/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 03:34:00 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Best-Practices]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=191</guid>
		<description><![CDATA[Not repeating yourself is a big part of writing stable code. You start writing the same code in three places and changes become a real pain...]]></description>
			<content:encoded><![CDATA[<p>Not repeating yourself is a big part of writing stable code. You start writing the same code in three places and changes become a real pain. More importantly, it&#8217;s very easy to forget something and end up with buggy programs.</p>
<p>But it&#8217;s easy to overlook a little bit of repetition. You&#8217;re in a hurry or dealing with an existing code base or whatever. But this is never a good idea as I learned&#8230;</p>
<p>We have an app where users pay a subscription fee through paypal. There are two separate actions &#8211; subscribe and renew &#8211; which send the user to paypal along with the necessary parameters (price, subscription type, etc.).</p>
<blockquote><p>
Two actions doing pretty much the same thing? Yep, that means repetition.
</p></blockquote>
<p>So, we were running some tests on the payment process and, to do so, had set the subscription fee to a penny. We got everything sorted, reset the subscription fees, and deployed our changes. Of course, we forget to reset the fees in the renew action.</p>
<p>The very next day, a customer renewed their subscription for the low, low price of one cent. So annoying. Anyway, can&#8217;t stress it enough &#8211; don&#8217;t repeat yourself.</p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/a-lesson-in-not-repeating-yourself/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

