[rspec-users] some fun functionality for all your specs

Courtenay court3nay at gmail.com
Fri Feb 16 18:20:21 EST 2007


I've found these two snippets of code useful and would love some feedback.

first, .should_have_valid_associations
usage:

context "A new Product" do
  specify "should have valid associations" do
    @product.should_have_valid_associations
  end
end

code: (thanks to Wilson/Defiler for converting to rspec)

module Spec
  module Expectations
    module Should
      class Base
        def have_valid_associations
          @target.save_without_validation
          @target.class.reflect_on_all_associations.each do |assoc|
            lambda { @target.send(assoc.name, true) }.should_not_raise
          end
          self
        end
      end
    end
  end
end


second, I had a problem where I'd renamed some fields in the model and
didn't want to manually spec out each method, but also didn't want to
go the 'null object' route.    assigns[:cart] = @cart = mock("cart")

    @cart.stub!(:attr_name).and_return('cart')
    @cart.stub!(:to_param).and_return('99')
    @cart.stub!(:class).and_return(Cart)

    Cart.content_columns.each { |c|
      @cart.stub!(c.name.to_sym)
    }
    Cart.reflect_on_all_associations.each do |assoc|
      @cart.stub!(assoc.name.to_sym).and_return([])
    end
    @cart.stub!(:name).and_return('cart')

As you can see it rapidly spirals out of control, but this snippet
sets up all the associations and field names as stubs.

Comments?


More information about the rspec-users mailing list