[Rspec-devel] Some handy rails helpers

Jay Levitt lists-rspec at shopwatch.org
Sun Jul 2 22:49:16 EDT 2006


I've been using these in spec_helper:

class Spec::Runner::ExecutionContext
   def form_should_have_fields(obj, fields)
     for field in fields
       response.body.should_have_tag :tag => "input",
         :attributes => { :name => "#{obj}[#{field}]" }
     end
   end
end

class Spec::Runner::Context
   def fields_should_start_empty(obj, *fields)
     fields.flatten.each do |f|
       specify "should have an empty #{f} field" do
         eval(obj.id2name + ".#{f}.should.be.nil")
       end
     end
   end

   def fields_cant_stay_empty(obj, *fields)
     fields.flatten.each do |f|
       specify "should disallow an empty #{f} field" do
         o = eval(obj.id2name)
         o.send("#{f}=", nil)
         o.should.not.be.valid
         o.errors.on(f).should.equal "can't be blank"
       end
     end
   end
end

---

Usage:

in a controller_spec.rb:

   specify "get the new receipt form" do
     get 'new'
     response.should.be.success
     response.should_render 'new'
     form_should_have_fields("receipt", ["vendor", "purchased_at"])
   end

in a model spec.rb, where :valid is a fixture for a valid receipt:

context "A newly created receipt" do
   setup do
     @receipt = Receipt.new
   end

   fields_should_start_empty(:@receipt, :vendor, :purchased_at)
end

context "An otherwise valid receipt" do
   fixtures :receipts

   setup do
     @receipt = receipts(:valid)
   end

   specify "should start out valid" do
     @receipt.should.be.valid
   end

   fields_cant_stay_empty(:@receipt, :vendor, :purchased_at)
end



More information about the Rspec-devel mailing list