Register now and start sharing your code snippets.
-->
Dynamic RSpec tests using plain old Ruby
Ruby posted 9 months ago by christian
Just happened to stumble upon the following article at caboo.se: Handy dynamic rspec tip.
I immediately found a way of simplifying a test case that involves testing that an ever increasing number of videos can be transcoded:
1 require File.dirname(__FILE__) + '/helper' 2 require File.dirname(__FILE__) + '/../lib/transcoder.rb' 3 4 context "Transcoder" do 5 6 Dir.glob('videos/*').each do |video| 7 it "should support #{video}" do 8 Transcoder.convert(video, "site/#{video}.flv")[:file_size].should > 0 9 end 10 end 11 end
You can also use it to test model validations:
1 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') 2 3 4 describe "Product" do 5 @@valid_product_attributes = { 6 :name => 'WTF', 7 :description => 'LOL', 8 :price => '10.0', 9 :tax => '22.0' } 10 11 12 before(:each) do 13 14 end 15 16 it "should create a new instance given valid attributes" do 17 Product.create!(@@valid_product_attributes) 18 end 19 20 @@valid_product_attributes.each do |name, value| 21 it "should not allow blank #{name}" do 22 lambda do 23 Product.create!(@@valid_product_attributes.except(name)) 24 end.should raise_error(ActiveRecord::RecordInvalid) 25 end 26 end 27 end