It enables us to test pagination and sorting (amongst other things) like this:
class CarsController...
PER_PAGE = 20
def index
@pages, @cars = paginate :cars, :per_page => PER_PAGE, :order => "make, model"
end
class CarsControllerTest < Test::Unit::TestCase...
def test_index_sorts_by_make_and_then_model_for_page_1
car1 = Car.create!(standard_params.merge(:make => "Fiat", :model => "Uno"))
car2 = Car.create!(standard_params.merge(:make => "Fiat", :model => "Bravo"))
car3 = Car.create!(standard_params.merge(:make => "Citroen", :model => "C2"))
with_constants CarsController, :PER_PAGE => 2 do
get :index
end
assert_equal [car3, car2], assigns(:assets)
end
def test_index_sorts_by_make_and_then_model_for_page_2
car1 = Car.create!(standard_params.merge(:make => "Fiat", :model => "Uno"))
car2 = Car.create!(standard_params.merge(:make => "Fiat", :model => "Bravo"))
car3 = Car.create!(standard_params.merge(:make => "Citroen", :model => "C2"))
with_constants CarsController, :PER_PAGE => 2 do
get :index, :page => 2
end
assert_equal_arrays [car1], assigns(:assets)
end
with_constants takes a class name and a hash of constant => value pairs, and yields to a block which is the code you want to call with the altered constants:
def with_constants(klass, constants_hash)
begin
old_constants = {}
constants_hash.each_pair do |name, value|
old_constants[name] = klass.send(:remove_const, name)
klass.const_set(name, value)
end
yield
ensure
constants_hash.each_pair do |name, value|
klass.send(:remove_const, name)
klass.const_set(name, old_constants[name])
end
end
end

0 comments:
Post a Comment