<?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>Improbabilidade Infinita &#187; testing</title>
	<atom:link href="http://cgweb.com.br/blog/category/testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://cgweb.com.br/blog</link>
	<description>Pois a vida é uma caixinha de surpresas.</description>
	<lastBuildDate>Fri, 19 Nov 2010 13:39:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Testing relationships in Rails</title>
		<link>http://cgweb.com.br/blog/2008/03/testing-relationships-in-rails/</link>
		<comments>http://cgweb.com.br/blog/2008/03/testing-relationships-in-rails/#comments</comments>
		<pubDate>Tue, 18 Mar 2008 13:42:00 +0000</pubDate>
		<dc:creator>filipe</dc:creator>
				<category><![CDATA[rails]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://improbabilidade.wordpress.com/?p=7</guid>
		<description><![CDATA[Ler este artigo em português I&#8217;ve been looking for an elegant way to test relationships using Rais, and think it&#8217;s interesting how so few people really care about it. Most simply say that it&#8217;s up to the framework to test it&#8217;s own functions. Yeah, right, has_many and belongs_to have been tested before, but you should [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://cgweb.com.br/blog/2008/03/testando-relacionamentos-no-rails/">Ler este artigo em português</a></p>
<p>I&#8217;ve been looking for an elegant way to test relationships using Rais, and think it&#8217;s interesting how so few people really care about it. Most simply say that it&#8217;s up to the framework to test it&#8217;s own functions. Yeah, right,  has_many and belongs_to have been tested before, but you should be aware that it&#8217;s up to you to check out the code you right. So, you have to make sure that a simple has_many :comments is really where it should be, so you should test it. Anyway, I listed some approaches I&#8217;ve found:</p>
<p>1 &#8211; Using fixtures:</p>
<p>At first, I thought about using fixtures, writing the relationships inside it (Rails 2.0). It&#8217;s a simple solution, but it has a downside. When we declare dependencies on the fixtures, and the relationship isn&#8217;t on the model, it&#8217;ll raise an error instead of a test failing. e.g.:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># post.rb</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Post <span style="color:#006600; font-weight:bold;">&amp;</span>lt; <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span><span style="color:#008000; font-style:italic;"># comment.rb</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Comment <span style="color:#006600; font-weight:bold;">&amp;</span>lt; <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># posts.yml</span>
&nbsp;
testing_relationships:
&nbsp;
  title: Hello World
&nbsp;
  body: Hello...
&nbsp;
<span style="color:#008000; font-style:italic;"># comments.yml</span>
&nbsp;
commenting_relationships:
&nbsp;
  body: I disagree!
&nbsp;
  author: Filipe Coimbra
&nbsp;
  post:  testing_relationships</pre></div></div>

<p>As I haven&#8217;t said that Comment belongs_to :post, when a test that calls comments.yml is called, an error will be raised.  Besides, the other dependency, Post has_many :comments won&#8217;t be tested.<br />
Besides, it&#8217;s not a cool thing to use fixtures as if they were tests. Besides, they&#8217;re not automatically documented.</p>
<p>2 &#8211; Again using fixtures:</p>
<p>After a while, I found <a href="http://www.nullislove.com/2008/01/08/testing-in-rails-part-7-activerecord-relationships/">this arcticle</a>, which also uses fixtures, but with a different approach (a little bit Rails 1.2-ish) just defining the relation through the foreign key. That way, no error will happen.<br />
It works, although you just have to test your own code, the rest is up to ActiveRecord. But, you may won&#8217;t like using fixtures because they may broke when you change your table structure.</p>
<p>3 &#8211; The wrong option that works:</p>
<p>Finally, I ended up using the most logical solution, that is writing ruby code, based <a href="http://errtheblog.com/posts/54-be-dee-dee-and-me">on this post by Err The Blog</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># post_spec.rb</span>
&nbsp;
describe Post <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
  before<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:each</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
    <span style="color:#0066ff; font-weight:bold;">@post</span> = Post.<span style="color:#9900CC;">new</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>   it <span style="color:#996600;">&quot;should be related to comments&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
    comment = Comment.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:body</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">&quot;Testing relationships&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
    <span style="color:#0066ff; font-weight:bold;">@post</span>.<span style="color:#9900CC;">comments</span> <span style="color:#006600; font-weight:bold;">&amp;</span>lt;<span style="color:#006600; font-weight:bold;">&amp;</span>lt; comment
&nbsp;
    <span style="color:#0066ff; font-weight:bold;">@post</span>.<span style="color:#9900CC;">comments</span>.<span style="color:#9900CC;">should</span> <span style="color:#9966CC; font-weight:bold;">include</span><span style="color:#006600; font-weight:bold;">&#40;</span>comment<span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># comment_spec.rb</span>
&nbsp;
describe Comment <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
  before<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:each</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
    <span style="color:#0066ff; font-weight:bold;">@comment</span> = Comment.<span style="color:#9900CC;">new</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  it <span style="color:#996600;">&quot;should be related to a post&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
    post = Post.<span style="color:#9900CC;">new</span>
&nbsp;
    <span style="color:#0066ff; font-weight:bold;">@comment</span>.<span style="color:#9900CC;">post</span> = post
&nbsp;
    <span style="color:#006600; font-weight:bold;">&lt;</span>span style=<span style="color:#996600;">&quot;text-decoration: line-through;&quot;</span><span style="color:#006600; font-weight:bold;">&gt;</span>@comment.<span style="color:#9900CC;">should</span> equal<span style="color:#006600; font-weight:bold;">&#40;</span>post<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&lt;/</span>span<span style="color:#006600; font-weight:bold;">&gt;</span>
&nbsp;
    <span style="color:#0066ff; font-weight:bold;">@comment</span>.<span style="color:#9900CC;">post</span>.<span style="color:#9900CC;">should</span> equal<span style="color:#006600; font-weight:bold;">&#40;</span>post<span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>It&#8217;s simple and easy, but&#8230; why is it wrong? When I write &#8220;@post.comments &lt;&lt; comment&#8221;, I&#8217;m calling a method comments on the object @post. As I didn&#8217;t declare that Post has_many :comments, this will be a missing method. Fortunately it works because rSpec won&#8217;t raise any errors, and just will tell us that the spec fails.<br />
Even so, I still prefer this approach as I won&#8217;t be dealing with fixtures.</p>
]]></content:encoded>
			<wfw:commentRss>http://cgweb.com.br/blog/2008/03/testing-relationships-in-rails/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Testando relacionamentos no Rails</title>
		<link>http://cgweb.com.br/blog/2008/03/testando-relacionamentos-no-rails/</link>
		<comments>http://cgweb.com.br/blog/2008/03/testando-relacionamentos-no-rails/#comments</comments>
		<pubDate>Tue, 18 Mar 2008 13:41:56 +0000</pubDate>
		<dc:creator>filipe</dc:creator>
				<category><![CDATA[rails]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://improbabilidade.wordpress.com/?p=6</guid>
		<description><![CDATA[Read this acticle in English Estive procurando por uma maneira elegante de testar relacionamentos utilizando Rails, e achei interessante como pouca gente está preocupada com isso. Na maioria das vezes, dizem simplesmente que isto é função do próprio framework. Tudo bem, o has_many e belongs_to (esqueça que existe o HBTM) já foram devidamente testados, mas [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://cgweb.com.br/blog/2008/03/testing-relationships-in-rails/">Read this acticle in English</a></p>
<p>Estive procurando por uma maneira elegante de testar relacionamentos utilizando Rails, e achei interessante como pouca gente está preocupada com isso. Na maioria das vezes, dizem simplesmente que isto é função do próprio framework. Tudo bem, o has_many e belongs_to (esqueça que existe o HBTM) já foram devidamente testados, mas é importante saber que o que cabe a você testar o que você escreve no seu código. Portanto, se você quer ter certeza que a linha has_many :comments realmente existe, você deve escrever um teste para ela. Então, resolvi listar algumas abordagens:</p>
<p>1 &#8211; Utilizando fixtures:</p>
<p>No começo, pensei em utilizar as fixtures, mas usando relacionamentos dentro delas. É uma solução simples, porém traz um revés. Quando utilizamos um relacionamento dentro das fixtures, e este relacionamento não está explicitado nos models, será retornado um erro, ao invés de uma falha. Por exemplo:</p>
<pre># post.rb

class Post &lt; ActiveRecord::Base

end# comment.rb

class Comment &lt; ActiveRecord::Base

end

# posts.yml

testing_relationships:

  title: Hello World

  body: Hello...

# comments.yml

commenting_relationships:

  body: I disagree!

  author: Filipe Coimbra

  post:  testing_relationships</pre>
<p>Como não foi explicitamente dito que Comment belongs_to :post, ao se executar a fixture comments.yml será retornado um erro. Além disso, o relacionamento contrário, Post has_many :comments não será testado.</p>
<p>2 &#8211; Novamente utilizando fixtures:</p>
<p>Depois, encontrei <a href="http://www.nullislove.com/2008/01/08/testing-in-rails-part-7-activerecord-relationships/">este artigo</a>, que também utiliza fixtures com uma abordagem diferente (e mais Rails 1.x) que é definir apenas a chave estrangeira na fixture. Assim, não seria retornado erro.<br />
É funcional, mas eu quero apenas testar se as linhas de relacionamento estão definidas nos models. O resto, fica por conta do ActiveRecord. Além disso, não quero usar fixtures como se fossem testes, já que, primeiro, não são documentadas automaticamente (como no caso dos métodos de teste) e porque, caso você mude a estrutura da sua tabela, poderá ter seus testes quebrados por causa das fixtures que não refletem as mudanças.</p>
<p>3 &#8211; A opção errada que funciona:</p>
<p>Acabei utilizando a solução mais lógica, e baseada <a href="http://errtheblog.com/posts/54-be-dee-dee-and-me">neste post do Err The Blog</a>.</p>
<pre># post_spec.rb

describe Post do

  before(:each) do

    @post = Post.new

  end  it "should be related to comments" do

comment = Comment.new(:body =&gt; "Testing relationships")

    @post.comments &lt;&lt; comment

    @post.comments.should include(comment)

  end

end

# comment_spec.rb

describe Comment do

  before(:each) do

    @comment = Comment.new

  end

it "should be related to a post"

    post = Post.new

    @comment.post = post

    @comment.should equal(post)

    @comment.post.should equal(post)

  end

end</pre>
<p>É simples, mas&#8230; por que é errada? Quando fazemos &#8220;@post.comments &lt;&lt; comment&#8221;, estamos chamando o método comments do objeto @post. Como não foi declarado que Post has_many :comments, este método não existirá. Ela funciona porque o rSpec não acusará o erro, e apenas retornará uma falha no teste.<br />
Ainda assim, prefiro essa solução porque eu não precisarei lidar com fixtures.</p>
]]></content:encoded>
			<wfw:commentRss>http://cgweb.com.br/blog/2008/03/testando-relacionamentos-no-rails/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

