Tuesday, July 30, 2013

Capybara HTML View Checking

I had wanted to do a decent job writing BDD tests for my views.  I was a bit surprised that the matchers were using the string form of the HTML.  I converted the string to a Capybara node in order to use the Capybara matchers.

HTML is tree-structured and my specs mirror  the HTML structure.  I check the parent node for correctness and then verify the children.  I had thought Capybara supported hierarchical specs using "within" but that doesn't seem to work for views.  It could be cockpit error on my part but Google searches didn't show any better way.

So I spent a little time adding to the RSpec DSL.  I wanted to have describe "scope into a subnode" of the current subject (the current subject being the equivalent of a DOM node).  I named the DSL "with_subnode".  With_subnode acts like describe with the ability to change the subject to a subnode.

The current subject is assumed to be a Capybara node.  with_subnode takes in the name of a Capybara::Node method (op:) to apply to the current subject plus any arguments (args:)

One starts by constructing a root_node using let( :root_node) do ... end.  This should be the string form as present in the rendered attribute.

The with_root_node method converts the root_node string into a Capybara::Node::Simple and makes it the subject of the do...end.

The example:


The code:

The code looks a bit odd. That has to do with the way RSpec builds tests. Each example/example_group is a meta-programmed class and one loses the lexical scoping. Each with_subnode clause is assigned a unique symbol. That symbol is used to retrieve the Capybara subject node from an associative array.

Unique symbols with an external associative array are used instead of let(). let() order evaluation along with inadvertent infinite recursion made that solution problematic.

The with_subnode clause is converted into two describe clauses. The inner describe clause is what the user placed in the do...end. The outer describe clause establishes the new subject.

An extra "it should_not be_nil" clause is added after the subject clause. This clause ensures the subject clause will be evaluated before the inner describe clause.

Tuesday, July 23, 2013

Controller Parameter Checking

Reference: rails/strong_parameters
Reference: active_record_validations.html#format
Reference: activemodel
Reference:

There are two main use cases.  The first to make sure that no extra parameters are accidentally passed into create/update operations.  This is to address any "mass assignment" vulnerability.

The second case is that RESTful controllers often have parameters not contained in the URL and hence not checked by the routing logic.  To validate those, we first construct a white-list:

nparams = params.permit( :my_param_a, :my_param_b, ...)

Note these are somewhat validated as being a basic type (see the reference above), but they aren't fully validated.

raw_parameters = { :my_param_a => "john@example.com", :my_param_b => "John", :admin => true } parameters = ActionController::Parameters.new(raw_parameters) puts "params: #{parameters}" cleaned = parameters.permit( :my_param_a,:my_param_b) puts "cleaned: #{cleaned}"
When executed:
params: {"my_param_a"=>"john@example.com", "my_param_b"=>"John", "admin"=>true} cleaned: {"my_param_a"=>"john@example.com", "my_param_b"=>"John"}
Oddly, input validation is not considered part of a controller; it seems to be model logic (see how-can-a-controller-manually-set-validation-errors-for-a-certain-field).  So we have to develop a Model that includes ActiveModel::Base in order to check the parameters.

Here is an example model which includes ActiveModel::Model
require 'active_record' require 'action_controller' class ParamCheck include ActiveModel::Model attr_accessor :my_param_a attr_accessor :my_param_b validates :my_param_a, presence: true, length: { minimum: 4 } validates :my_param_b, presence: true end
Some test code:
pc = ParamCheck.new puts pc.valid? pc.errors.full_messages.each do |err| puts err.inspect end
And the output:
false "My param a can't be blank" "My param a is too short (minimum is 4 characters)" "My param b can't be blank"
Using the cleaned parameters in the constructor:
pc2 = ParamCheck.new( cleaned) puts pc2.valid? pc2.errors.full_messages.each do |err| puts err.inspect end
Results in:
true

Adding checking to a controller

Each controller action is responsible for handling parameter white-list and required presence.

The idea is to define a nested class within the controller that is responsible for parameter checking. To avoid having a class per action, one ensures that named parameters are used consistently across all actions. For example, params[:email] should always be an e-mail address. Don't use names like :arg1 across multiple actions where it is an integer in one and an e-mail address in another.

The nested class then supplies validators for each parameter name. The validates should not check for presence as that was already handled by the action.

After the white-list and requires, one instantiates the CheckParams class using the cleaned-up parameters. One then checks to see if the instantiation is valid. If not, one produces a response with status 400 (bad request).

render :text => "400 Bad Request", :status => 400

Friday, July 19, 2013

Toggle Panel for Twitter Bootstrap

I had searched for a toggle panel widget and obtained one that sort-of worked from: where-are-collapsible-panels-in-this-framework

It was designed for JQuery and my toggle icon kept appearing on a line by itself.  I'm a relative JQuery newbie but old enough to know that writing highly chained JQuery code is someone's way of ensuring job security.

I refactored the code to use variables, added comments and substituted bootstrap icons for JQuery icons.  Here is the revised widget:


$.fn.togglepanels = function() { return this.each(function() { $(this).addClass("ui-accordion ui-accordion-icons ui-widget ui-helper-reset"); $h3 = $(this).find("h3"); $h3.addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-top ui-corner-bottom"); // Add hover so this is apparent that it is a control $h3.hover(function() { $(this).toggleClass("ui-state-hover"); }); // Add the decorative icon $h3.prepend('<span class="toggle-panel-icon icon-plus-sign"></span>'); $h3.click(function() { $h3 = $(this); $h3.toggleClass("ui-accordion-header-active ui-state-active ui-state-default ui-corner-bottom"); $icons = $h3.children(".toggle-panel-icon"); $icons.toggleClass("icon-plus-sign icon-minus-sign"); // Stop any animations on content $content = $h3.next(); $content.stop(true, true); // Show/hide using a sliding animation $content.slideToggle(); return false; }); // Add styling classes to the content and initial hide it $content = $h3.next(); $content.addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom"); $content.hide(); // Content is returned by default }); };

Thursday, July 18, 2013

Note to self: SCSS and background images

I use background images in my .css.  When I deployed my app to Heroku, those images weren't showing up.

I used Google's developer tools and looked at the page's resources.  Those images are flagged as "not found".  Looking at the links, they were different-looking from my other precompuled assets.

Turned out that rather than url("image.png"), I needed url( image_path( "image.png")) in my .scss files.

Wednesday, July 17, 2013

Forms with Twiiter Bootstrap and Rails

I was using Rails's "form_for".  I had styled my form using 'form-horizontal'.  Everything looked good until I submitted a form with errors.  The form styling looked awful.

The solution can be found at the RailsApps project on GitHub.  I changed to SimpleForm using the directions provided and the presentation looks good.

Saturday, July 13, 2013

Note to self: run rspec in project directory only

I noticed this when developing routing specs. Usually I run the command from the directory I'm working in. In this case, running "bundle exec rspec foo_routing_spec.rb" would fail. Running it in the parent directory as "bundle exec rspec spec/routing/foo_routing_spec.rb" works.

Templatized / Metaprogramming Testing

We often think of rules/specifications as applying to more than one object.  When I first began learning Ruby, I had followed Hartl's examples in writing tests and discovered that I was doing a lot of copy-and-paste.  That didn't feel right but I didn't know to do.  I wanted to do something like "foreach sign-in state { foreach page { verify page }}".

During the conversion of project to Cabybara 2.0, I noticed that descriptions could be tagged with additional hash key-value pairs.  They had something like:
describe "this test", :type => "feature" do

Interestingly, there is a note in rspec / rspec-core on metadata.  After some playing, I discovered a working design pattern.


  user_states = ["visiting","signed in", "admin"]

  user_states.each do |user_state|
    describe "for #{user_state} users", :user_state => user_state do
      let( :user_state) { example.metadata[:user_state] }

      let(:user) do
        user = nil
        case user_state
        when "signed in"
          user = FactoryGirl.create(:user)
        when "admin"
          user = FactoryGirl.create(:admin)
        end
        user
      end

      before do
        sign_in user unless user.nil?
      end

      all_static_page_names.each do |pg|
        describe pg, :page_name => pg do

          let(:page_name) { example.metadata[:page_name] }
          let(:pa) { PageAttributes.new( page_name) }

          before do
            # puts "          user state #{user_state}"
            pa.path = path_for_static_page( page_name)
            # puts "        pa: #{pa.inspect}"
            visit pa.path
          end

          it { should have_title( pa.title) }
          it { should_not have_title(full_title('Edit user')) }

          it { should have_link('Contact', href: contact_path) }
          it { should have_link('About', href: about_path) }
          
          if( user_state=="visiting") then
            it { should have_link('Sign in', href: signin_path) }
          else
            it { should have_link('Sign out', href: signout_path) }
          end

        end
      end

    end

  end

I have a few helper routines in my utilities. One provides the array of page names, another returns the page attributes for a page. The last returns the path to a page given a page name. I had to keep the path one separate as when I tried to include in the PageAttribute constructor, something was wrong and I couldn't access the *_path variables.