From 967b9fc67c8fbe5f96ecfb710b08993fed0f66da Mon Sep 17 00:00:00 2001 From: Matt Jankowski Date: Sat, 20 Sep 2008 16:06:28 -0400 Subject: [PATCH] add an :equals option to should_assign_to which checks that the assigned instance variable is equal to the eval of the string passed to the option --- lib/shoulda/controller/macros.rb | 18 +++++++++++++++--- test/functional/posts_controller_test.rb | 5 ++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/lib/shoulda/controller/macros.rb b/lib/shoulda/controller/macros.rb index 8a4bc0c8..711cecbd 100644 --- a/lib/shoulda/controller/macros.rb +++ b/lib/shoulda/controller/macros.rb @@ -101,19 +101,31 @@ def should_not_set_the_flash # # Options: # * :class - The expected class of the instance variable being checked. + # * :equals - A string which is evaluated and compared for equality with + # the instance variable being checked. # # Example: # # should_assign_to :user, :posts # should_assign_to :user, :class => User + # should_assign_to :user, :equals => '@user' def should_assign_to(*names) opts = names.extract_options! names.each do |name| test_name = "assign @#{name}" - test_name << " as #{opts[:class]}" if opts[:class] + test_name << " as class #{opts[:class]}" if opts[:class] + test_name << " which is equal to #{opts[:equals]}" if opts[:equals] should test_name do - assert assigns(name.to_sym), "The action isn't assigning to @#{name}" - assert_kind_of opts[:class], assigns(name.to_sym) if opts[:class] + assigned_value = assigns(name.to_sym) + assert assigned_value, "The action isn't assigning to @#{name}" + assert_kind_of opts[:class], assigned_value if opts[:class] + if opts[:equals] + instantiate_variables_from_assigns do + expected_value = eval(opts[:equals], self.send(:binding), __FILE__, __LINE__) + assert_equal expected_value, assigned_value, + "Instance variable @#{name} expected to be #{expected_value} but was #{assigned_value}" + end + end end end end diff --git a/test/functional/posts_controller_test.rb b/test/functional/posts_controller_test.rb index 75b214e7..9e34b031 100644 --- a/test/functional/posts_controller_test.rb +++ b/test/functional/posts_controller_test.rb @@ -64,10 +64,13 @@ def setup get :index, :user_id => users(:first) end should_respond_with :success - should_assign_to :user, :class => User + should_assign_to :user, :class => User, :equals => 'users(:first)' should_fail do should_assign_to :user, :class => Post end + should_fail do + should_assign_to :user, :equals => 'posts(:first)' + end should_assign_to :posts should_not_assign_to :foo, :bar end