[rspec-users] a better "should have valid associations"

aslak hellesoy aslak.hellesoy at gmail.com
Thu Mar 29 05:18:29 EDT 2007


I really like it. Good to see custom matchers for RSpec are being put
to use too.

Does anyone think it would be a good idea to add this to spec:rails?

Aslak

On 3/29/07, Courtenay <court3nay at gmail.com> wrote:
> This is pretty much the same as last time around, if you recall.
>
> Thanks to Wilson for converting to the new form. I've added a few
> lines. Basically, it iterates over your model associations and does
> two things.
>
> - First, just try to call the association. Usually fixes speeling
> erors or other such silliness.
>
> - Second, try to find a record with an :include on the association.
> This actually hits the DB and will tell you if you have lingering
> associations on deleted models.  Page.find(:first, :include => :user)
>
> (Note: I usually feel that testing associations is really testing the
> framework, and such code belongs in the framework itself. Also, this
> won't check if you removed some associations. And it won't check for
> polymorphs either.)
>
> Put this somewhere handy and require it into spec_helper.
>
> ========================================
>
> module ActiveRecordMatchers
>  class HaveValidAssociations
>    def matches?(model)
>      @failed_association = nil
>      @model_class = model.class
>
>      model.class.reflect_on_all_associations.each do |assoc|
>        begin
>          model.send(assoc.name, true)
>          model.class.send('find', :first, :include => assoc.name)
>        rescue ActiveRecord::EagerLoadPolymorphicError
>          # nothing. Can't find :include a polymorph. This requires a
> better test.
>        rescue => err
>          @failed_association = "#{assoc.name} // #{err}"
>        end
>      end
>      !@failed_association
>    end
>
>    def failure_message
>      "invalid association \"#{@failed_association}\" on #{@model_class}"
>    end
>  end
>
>  def have_valid_associations
>    HaveValidAssociations.new
>  end
> end
>
> ========================================
>
> Put this in your model spec.
>
> context "A new Page" do
>  include ActiveRecordMatchers
>
>  specify "should have valid associations" do
>    object = Page.new
>    object.should have_valid_associations
>  end
> end
>
> ========================================
>
>
> court3nay
> http://blog.caboo.se
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>


More information about the rspec-users mailing list