<?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>A Waage Blog &#187; Ruby</title>
	<atom:link href="http://qugstart.com/blog/tag/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://qugstart.com/blog</link>
	<description>Ruby, Rails, Life</description>
	<lastBuildDate>Thu, 10 Nov 2011 00:35:02 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Ruby floats, BigDecimals and money (currency)</title>
		<link>http://qugstart.com/blog/ruby-and-rails/ruby-floats-bigdecimals-and-money-currency/</link>
		<comments>http://qugstart.com/blog/ruby-and-rails/ruby-floats-bigdecimals-and-money-currency/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 00:29:22 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[RSpec]]></category>
		<category><![CDATA[Rails Testing]]></category>
		<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[BigDecimals]]></category>
		<category><![CDATA[currency]]></category>
		<category><![CDATA[Floats]]></category>
		<category><![CDATA[money]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=151</guid>
		<description><![CDATA[Fellow Ruby-ers, please be warned!!! DO NOT use Ruby floats when performing arithmetic calculations involving money!
My calculations work in IRB, so I was really confused when I ran into this weird situation where (what I thought was) a simple arithmetic calculation led to strange results in my unit tests (I cannot stress the importance of [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Fellow Ruby-ers, please be warned!!! DO NOT use Ruby floats when performing arithmetic calculations involving money!</strong></p>
<p>My calculations work in IRB, so I was really confused when I ran into this weird situation where (what I thought was) a simple arithmetic calculation led to strange results in my unit tests (I cannot stress the importance of good unit testing!).</p>
<p>My backend calculation was basically this (simplified):</p>
<pre lang='ruby' class='prettyprint'>
# arbitrary amounts for these two variables
percentage = 12
total_in_cents = 400

discount = percentage.to_f / 100.0
total_in_float = total_in_cents.to_f * 100.0
new_price = (total_in_float * discount ).round / 100
</pre>
<p>Now, it&#8217;s pretty obvious that 12% of (400 cents) $4.00 should just be $0.48 (48 cents)<br />
However, my barrage of unit tests kept producing strange results where a simple calculation was returning incorrect results. Doing some research, I discovered a series of articles worth reading including:</p>
<ul>
<li> <a href="https://makandracards.com/makandra/1505-invoices-how-to-properly-round-and-calculate-totals">How to properly round and calculate totals</a> </li>
<li><a href="https://makandracards.com/makandra/1178-bigdecimal-arithmetic-in-ruby">BigDecimal arithmetic in Ruby</a></li>
</ul>
<p>Also, check out the <a href="https://github.com/collectiveidea/money">Money gem</a> &#8211; I&#8217;ve never used it personally, but <a href="http://stackoverflow.com/questions/1019939/ruby-on-rails-best-method-of-handling-currency-money">people have said good things about it</a>. </p>
<p>Heeding the advice I found online, I re-wrote all my money-related calculations using BigDecimals instead of Floats.</p>
<pre lang='ruby' class='prettyprint'>
percentage = 12
total_in_cents = 400
discount = BigDecimal(percentage.to_s) / 100
total_in_float = BigDecimal(total_in_cents.to_s) * 100
new_price = (total_in_float * discount ).to_i / 100
</pre>
<p>After switching over from Floats to BigDecimals, my unit tests all passed!<br />
Lesson learned and hope this heads-up helps you guys too. </p>
<p><strong>Summary:</strong><br />
<strong>Use BigDecimals for money calculations and remember to write good UNIT TESTS!!</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/ruby-and-rails/ruby-floats-bigdecimals-and-money-currency/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RSpec Request Spec to Test Rails / Grape API Functionality</title>
		<link>http://qugstart.com/blog/ruby-and-rails/rspec-request-spec-to-test-rails-grape-api-functionality/</link>
		<comments>http://qugstart.com/blog/ruby-and-rails/rspec-request-spec-to-test-rails-grape-api-functionality/#comments</comments>
		<pubDate>Thu, 26 May 2011 08:29:08 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[RSpec]]></category>
		<category><![CDATA[Rails Testing]]></category>
		<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Basic Authentication]]></category>
		<category><![CDATA[basic_auth]]></category>
		<category><![CDATA[Grape]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[request]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=106</guid>
		<description><![CDATA[I finally got around to trying Grape &#8211; a &#8220;RESTful API microframework built to easily and quickly produce APIs for Ruby-based web applications&#8221;. This is a project still in baby stages, but has a lot of potential and worth exploring for anyone creating a Rack-based API in Ruby, not necessarily Rails!
Now, after creating a pretty [...]]]></description>
			<content:encoded><![CDATA[<p>I finally got around to trying <a href="https://github.com/intridea/grape/wiki">Grape</a> &#8211; a &#8220;RESTful API microframework built to easily and quickly produce APIs for Ruby-based web applications&#8221;. This is a project still in baby stages, but has a lot of potential and worth exploring for anyone creating a Rack-based API in Ruby, not necessarily Rails!</p>
<p>Now, after creating a pretty basic API that used HTTP Basic Authentication, I was inclined to write some RSpec tests to make sure my API was working the way I thought it was (.. or because I am obsessed with well-tested, beautiful code..). </p>
<p>After some thought, I decided that the best way to test my API was with <a href="http://relishapp.com/rspec/rspec-rails/v/2-6/dir/request-specs/request-spec">RSpec &#8220;request&#8221; specs</a>. Now, if you are at all relatively new to RSpec (I was a Test::Unit kinda guy before), it might not be completely obvious that &#8220;request specs&#8221; are basically what I have come to know as &#8220;integration tests&#8221;, testing high-level functionality that spans multiple controllers and multiple requests &#8211; (think: a user&#8217;s interaction with the app).  </p>
<p>My reasoning for choosing request specs is because I want to test specific API URL endpoints routed the way I expected. (Routing is handled magically by Grape with a simple mount in the config/routes.rb file). API testing just kinda makes sense to handle in request specs.</p>
<p>Anyways, I ran into a couple issues because in REQUEST specs, you do not have access to the @request object (haha?), as you do in controller specs. Now, in order to mock HTTP Basic Authentication, you need to mock the request object to send headers along with the GET request. </p>
<p>Well, solution: It turns out you can pass headers into your get() method! I only wish I had discovered that an hour ago!</p>
<p>Here&#8217;s a simple excerpt from my API request specs that shows how to mock the HTTP basic authentication and test your API functionality:</p>
<p>With NO basic auth, it&#8217;s just a simple GET request</p>
<pre class="prettyprint" lang="ruby">
  it 'should return a 401 with no basic auth to /api/v1/rewards' do
    get '/api/v1/rewards'
    response.code.should == '401'
    response.body.should == "Unauthorized - Please check your username and password"
  end
</pre>
<p>To mock the basic auth, simply pass header hash as argument to the GET request! No need to access the request object here.</p>
<pre class="prettyprint" lang="ruby">
  it 'should return a 200 with valid basic auth to /api/v1/rewards' do
    # Uses basic_auth helper method
    credentials = basic_auth('testuser','test')
    get '/api/v1/rewards', nil, {'HTTP_AUTHORIZATION' =>  credentials }
    response.code.should == '200'
    response.body.should == "..."
  end

# You can define this at the bottom of your spec file, or in spec_helper for convenience
def basic_auth(user, password)
  ActionController::HttpAuthentication::Basic.encode_credentials user, password
end
</pre>
<p>Hope this helps someone else. Now go write some request specs! <img src='http://qugstart.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/ruby-and-rails/rspec-request-spec-to-test-rails-grape-api-functionality/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ruby Multi-level Nested Hash Value</title>
		<link>http://qugstart.com/blog/uncategorized/ruby-multi-level-nested-hash-value/</link>
		<comments>http://qugstart.com/blog/uncategorized/ruby-multi-level-nested-hash-value/#comments</comments>
		<pubDate>Sat, 19 Mar 2011 03:27:22 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Hash]]></category>
		<category><![CDATA[initializers]]></category>
		<category><![CDATA[multi-level]]></category>
		<category><![CDATA[Nested]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=81</guid>
		<description><![CDATA[Often in my Ruby code or Rails application, I will need to find a value in a nested hash. Frequently this also comes in handy when dealing with JSON and parsing JSON to a hash. For example, I might have a hash of user information that looks like this:

user_hash = {:id => 1, :name => [...]]]></description>
			<content:encoded><![CDATA[<p>Often in my Ruby code or Rails application, I will need to find a value in a nested hash. Frequently this also comes in handy when dealing with JSON and parsing JSON to a hash. For example, I might have a hash of user information that looks like this:</p>
<pre class='prettyprint' lang='ruby'>
user_hash = {:id => 1, :name => 'John doe', :extra => {:birthday => {:month => 11, :day => 16, :year => 1951}}}
</pre>
<p>Now, when I want to find the birthday year, I have to do something messy like this:</p>
<pre class='prettyprint' lang='ruby'>
year = user_hash[:extra] &#038;&#038; user_hash[:extra][:birthday] &#038;&#038; user_hash[:extra][:birthday][:year]
</pre>
<p>How inconvenient is this?! Every level of the hash I am checking for existence of the hash-key. Here&#8217;s a helper method that I use so that I can avoid these verbose statements and get the value I want in 1 line. It adds a &#8216;hash_val&#8217; method to any hash, and takes in the hash-keys as arguments. If one of the nested hash keys is missing, it will simply return nil.</p>
<pre class='prettyprint' lang='ruby'>
# I usually define this in an initializer, so it can be used all over my app:
# Eg. Place in config/initializers/hash_val.rb
class Hash
  # Fetch a nested hash value
  def hash_val(*attrs)
    attr_count = attrs.size
    current_val = self
    for i in 0..(attr_count-1)
      attr_name = attrs[i]
      return current_val[attr_name] if i == (attr_count-1)
      return nil if current_val[attr_name].nil?
      current_val = current_val[attr_name]
    end
    return nil
  end
end
</pre>
<p>Now, getting a nested hash value is so easy!</p>
<pre class='prettyprint' lang='ruby'>
user_hash.hash_val(:extra, :birthday, :year)
 => 1951
</pre>
<p>And, if the hash-key does not exist, it simply returns nil:</p>
<pre class='prettyprint' lang='ruby'>
user_hash.hash_val(:extra, :trouble)
=> nil
</pre>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/uncategorized/ruby-multi-level-nested-hash-value/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Facebook base64 url decode for signed_request</title>
		<link>http://qugstart.com/blog/ruby-and-rails/facebook-base64-url-decode-for-signed_request/</link>
		<comments>http://qugstart.com/blog/ruby-and-rails/facebook-base64-url-decode-for-signed_request/#comments</comments>
		<pubDate>Tue, 08 Feb 2011 20:27:05 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[Facebook API]]></category>
		<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[base64]]></category>
		<category><![CDATA[base64_url_decode]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[signed_request]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=75</guid>
		<description><![CDATA[I ran into a problem as I was trying to decode and parse the Facebook signed_request for their new Registration plugin (http://developers.facebook.com/docs/plugins/registration).
Folowing the PHP example, I attempted to decode and read the signed_request returned by Facebook. Unfortunately, it seemed like the decoded JSON returned was malformed! It was missing the end hash character &#8220;}&#8221;. This [...]]]></description>
			<content:encoded><![CDATA[<p>I ran into a problem as I was trying to decode and parse the Facebook signed_request for their new Registration plugin (<a href="http://developers.facebook.com/docs/plugins/registration">http://developers.facebook.com/docs/plugins/registration</a>).</p>
<p>Folowing the PHP example, I attempted to decode and read the signed_request returned by Facebook. Unfortunately, it seemed like the decoded JSON returned was malformed! It was missing the end hash character &#8220;}&#8221;. This may not happen in all cases, but the reason is due to the padding in Base64 encoding (See <a href="http://en.wikipedia.org/wiki/Base64#URL_applications">Base64 for URLs in Wikipedia</a>).</p>
<p>To account for the padding in Base64, I used the following helper method to do the base64_url_decode. Hope it helps someone else trying to base64 decode Facebook&#8217;s signed_request in Ruby on Rails!:</p>
<pre class='prettyprint' lang='ruby'>
 def base64_url_decode(str)
   str += '=' * (4 - str.length.modulo(4))
   Base64.decode64(str.tr('-_','+/'))
 end
</pre>
<p>Notice there&#8217;s two things that must happen before decoding the string: </p>
<ol>
<li>Pad the encoded string with &#8220;=&#8221;</li>
<li>Replace the character &#8216;-&#8217; with &#8216;+&#8217;, and &#8216;_&#8217; with &#8216;/&#8217;</li>
</ol>
<p>I wish Facebook mentioned this clearly on their API !</p>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/ruby-and-rails/facebook-base64-url-decode-for-signed_request/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Converting Timezones in Ruby: TZInfo</title>
		<link>http://qugstart.com/blog/ruby-and-rails/converting-timezones-in-ruby-tzinfo/</link>
		<comments>http://qugstart.com/blog/ruby-and-rails/converting-timezones-in-ruby-tzinfo/#comments</comments>
		<pubDate>Sun, 26 Oct 2008 01:14:13 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[timezone]]></category>
		<category><![CDATA[tzinfo]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=7</guid>
		<description><![CDATA[In a recent Rails project, I was trying to figure out how to allow users to view any email&#8217;s &#8220;Date:&#8221; header in his/her own timezone. Here&#8217;s a short explanation about how I accomplished this using Ruby&#8217;s TZInfo gem!
Purpose:
If an email was sent out from New York, the header would contain a Date string like the [...]]]></description>
			<content:encoded><![CDATA[<p>In a recent Rails project, I was trying to figure out how to allow users to view any email&#8217;s &#8220;Date:&#8221; header in his/her own timezone. Here&#8217;s a short explanation about how I accomplished this using Ruby&#8217;s TZInfo gem!</p>
<p>Purpose:<br />
If an email was sent out from New York, the header would contain a Date string like the following (notice the offset):</p>
<pre lang="bash" class="prettyprint">
Fri, 24 Oct 2008 18:35:07 -0400 (EST)
</pre>
<p>Now, it makes sense for a user in Los Angeles to be able to view the Date/time as 15:35 pm, while a user in New York City should be able to view it as 18:35pm.</p>
<p>Here&#8217;s what I did.</p>
<p>Of course, I installed TZinfo first:</p>
<pre lang="bash" class="prettyprint">
%>sudo gem install tzinfo
</pre>
<p>Each user should have a timezone associated. Try the following method for a list of timezones in US:</p>
<pre lang="rails" class="prettyprint">
 >>TZInfo::Country.get('US').zone_identifiers
</pre>
<p>Let&#8217;s take two users as an example. We have lakersfan is on the west coast, and knicksfan is on the east coast:</p>
<pre lang="rails" class="prettyprint">
>> lakersfan.timezone = TZInfo::Timezone.get('America/Los_Angeles')
>> knicksfan.timezone = TZInfo::Timezone.get('America/New_York')
</pre>
<p>Given a date/time string like the following (could be taken from the email header or elsewhere):</p>
<pre lang="rails" class="prettyprint">
>>timestring = "Fri, 24 Oct 2008 18:35:07 -0400 (EST)"
</pre>
<p> first call Time.parse(timestring) which will create a time object with offset info. **Note that this is different from calling timestring.to_time (which will disregard offset info and store the Time object as UTC).</p>
<pre lang="rails" class="prettyprint">
>> timestring = "Fri, 24 Oct 2008 18:35:07 -0400 (EST)"
>> Time.parse(timestring)
=> Fri Oct 24 18:35:07 -0400 2008 #Stores the Time object with offset
>> timestring.to_time
=> Fri Oct 24 18:35:07 UTC 2008 #Incorrect - the offset is ignored
</pre>
<p>Now, once you&#8217;ve got the Time object in proper format (with offset), you can just call the &#8216;utc&#8217; method to convert the time into UTC format:</p>
<pre lang="rails" class="prettyprint">
>> utctime = Time.parse(timestring).utc
</pre>
<p>Lastly, once the time is in UTC format, you can use any user&#8217;s timezone object to call &#8216;utc_to_local&#8217; method and convert that utc time into the user&#8217;s timezone!</p>
<pre lang="rails" class="prettyprint">
>> lakersfan.tz.utc_to_local(utctime)
=> Fri Oct 24 15:35:07 UTC 2008
>> knicksfan.tz.utc_to_local(utctime)
=> Fri Oct 24 18:35:07 UTC 2008
</pre>
<p>Voila! Lakers fan (west coast) sees the time as 15:35, while the Knicks fan (on east coast) sees the time as 18:35 &#8211; the same as the email header.</p>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/ruby-and-rails/converting-timezones-in-ruby-tzinfo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Functional Testing Cookies in Ruby on Rails 1.2.3</title>
		<link>http://qugstart.com/blog/ruby-and-rails/functional-testing-cookies-in-ruby-on-rails-123/</link>
		<comments>http://qugstart.com/blog/ruby-and-rails/functional-testing-cookies-in-ruby-on-rails-123/#comments</comments>
		<pubDate>Mon, 13 Oct 2008 07:33:18 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[Rails Testing]]></category>
		<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[assert_cookie]]></category>
		<category><![CDATA[cookies]]></category>
		<category><![CDATA[functional testing]]></category>
		<category><![CDATA[persistent cookies]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=5</guid>
		<description><![CDATA[After spending a good couple hours + trying to figure out why my functional tests were failing when working with cookies, I came across a couple great resources for rails + testing cookies.
Here&#8217;s a good basic explanation of using cookies on Pluit solutions website.  Then I came across the Robby on Rails blog that [...]]]></description>
			<content:encoded><![CDATA[<p>After spending a good couple hours + trying to figure out why my functional tests were failing when working with cookies, I came across a couple great resources for rails + testing cookies.</p>
<p>Here&#8217;s a good basic explanation of using cookies on <a title="Pluit Solutions" href="http://www.pluitsolutions.com/2006/08/02/rails-functional-test-with-cookie/">Pluit solutions</a> website.  Then I came across the <a title="Robby on Rails" href="http://www.robbyonrails.com/articles/2006/08/28/testing-cookies-in-ruby-on-rails">Robby on Rails</a> blog that led me to understand (and misunderstand) the <a title="assert_cookie" href="http://blog.brightredglow.com/articles/2006/08/27/assert_cookie-for-ooey-gooey-fun">asssert_cookie</a> plugin.</p>
<p>However, I was still having a lot of trouble figuring out why I was setting my @request.cookies['foo'] in my functional test, but later (in the same test method) checking for cookies['foo'] and not finding anything in the cookie jar!</p>
<p>I then tried setting cookies['foo'] in my controller test, but found that when I did a check for the existance of that cookie in my actual controller code, it was not there! I thought that I should be able to set up a cookie in a test and have my controller recognize it. This is true, however, not by setting cookies['foo'].</p>
<p>So&#8230; I opened up a blank controller and functional test and began testing out different combinations to find out exactly what was going on. I hope this little example helps to save someone else&#8217;s precious time. Here it goes&#8230;</p>
<p>This is the controller I will be referring to for my example tests:</p>
<pre lang="rails" class="prettyprint">========= controller
  def foo
    if cookies['oreo'] == 'yesitis'
      @info =  "Oreos are tasty"
    else
      @info = "Only Milk here"
    end
     render :nothing => true
  end</pre>
<p>1. In your functional test, do not test for presence of a cookie after a get request to a particular action, <strong>unless </strong>the action you are testing specifically sets up that cookie.  In other words, if your controller action is not setting the cookie, do not test for that cookie&#8217;s presence.</p>
<p>In the above controller, no cookies are ever being set. Therefore, testing for the presence of a cookie after the get request (in a test method) will return false.</p>
<p>In other words, the cookie is recognized by the controller, however, notice that cookies['oreo'] is nil after the get request:</p>
<pre lang="rails" class="prettyprint">  def test_oreo
    @request.cookies['oreo'] = CGI::Cookie.new("oreo", "yesitis")
    get :foo
    assert_equal({}, @response.cookies)
    assert_equal(nil, cookies['oreo'])
    #Assert cookie will be nil here so do not test it:
    #assert_cookie <img src='http://qugstart.com/blog/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> reo
    puts assigns['info'] #"Oreos are tasty"
  end</pre>
<p>Note:<br />
1. After your get request, the @response.cookies will be empty<br />
2. After your get request, cookies['oreo'] will still be nil.<br />
3. After your get request, you cannot use assert_cookie because it will be nil</p>
<p>2. If your controller action expects a cookie to be there, you <strong>cannot </strong>set it up in your functional test by assigning:</p>
<li> cookies['oreo'] = true  (<span style="color: #ff0000;"><em>incorrect</em></span>) OR</li>
<li>@request.cookies['oreo'] = true   (<span style="color: #ff0000;"><em>incorrect</em></span>)</li>
<p>The only way to set up your cookie for a subsequent request, so that your controller will see it is:</p>
<ul>
<li>@request.cookies['oreo'] = CGI::Cookies.new(&#8217;oreo&#8217;, true)    (<span style="color: #339966;">correct</span>)</li>
</ul>
<pre lang="rails" class="prettyprint">  #INCORRECT
  def test_oreo
    cookies['oreo'] = 'yesitis'
    get :foo
    puts assigns['info'] #"Only Milk here"
  end

#INCORRECT
  def test_oreo
    cookies['oreo'] =  CGI::Cookie.new("oreo", "yesitis")
    get :foo
    puts assigns['info'] #"Only Milk here"
  end

#INCORRECT
  def test_oreo
    @request.cookies['oreo'] = 'yesitis'
    get :foo
    puts assigns['info'] #"Only Milk here"
  end</pre>
<p><strong>The only way to set up your cookie in a functional test and have your controller recognize it.</strong></p>
<pre lang="rails" class="prettyprint">#CORRECT
  def test_oreo
    @request.cookies['oreo'] = CGI::Cookie.new("oreo", "yesitis")
    get :foo
    puts assigns['info'] # Will print out "Oreos are tasty"
  end</pre>
<p>3. Avoid the temptation to use symbols in your tests with cookies.</p>
<ul>
<li> cookies[:foo]   -> BAD</li>
<li> cookies['foo']   -> GOOD</li>
</ul>
<p>4. Only use <strong>assert_cookie</strong> (plugin: see above for link) if you are testing that the controller action is creating a new cookie.</p>
<p>5. If you are testing multiple actions and redirects from one action to another action in the same controller, you do not need to set the cookie before each action, explicitly. The cookie will remain in the @request object that you created in the setup method of your test.</p>
<p>EXAMPLE TWO (Testing persistent cookies)<br />
You DONT set up the cookie for each subsequent request.<br />
It does &#8220;persist&#8221; throughout your test-method because you are<br />
using the same @request object!!</p>
<pre lang="rails" class="prettyprint">========controller
  def foo
    if cookies['oreo'] == 'yesitis'
	puts "Foo has OREO"
    else
 	puts "Foo has NOTHING"
    end
      redirect_to :action => :bar
      return true
  end

  def bar
    if cookies['oreo'] == 'yesitis'
      puts "Oreos are tasty"
    else
      puts "Only Milk here"
    end
     render :nothing => true
  end

========= Test
  def test_oreo
   @request.cookies['oreo'] =  CGI::Cookie.new('oreo', "yesitis")
    get :foo    #OUTPUTS: Foo has OREO

    # COOKIE PERSISTS HERE!!
    # Don't need to explicitly set cookie again in the
    # @request.cookies object
    get :bar   #OUTPUTS: Oreos are tasty
  end</pre>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/ruby-and-rails/functional-testing-cookies-in-ruby-on-rails-123/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

