MTJ Hax

MiniTest version of RSpec any_instance

Posted in code, ruby, ruby on rails by mtjhax on August 30, 2013

Using MiniTest in Rails apps, I have been missing the RSpec any_instance method:

MyClass.any_instance.stubs(:a_method)

There are other ways to stub in MiniTest but any_instance is convenient and expressive, so I wrote my own quickie version based on aliasing. I call it all_instances to avoid any problems if also using RSpec. Drop this in a file in test/support and make sure it is included in your test_helper.rb:

# this allows a MiniTest test to stub out a method on all instances of a class
# examples:
#
# MyClass.all_instances.stub(:foo, 'bar') do
#   MyClass.new.foo.must_equal 'bar'
# end
#
# MyClass.all_instances.stub(:foo, 'bar')
# MyClass.new.foo.must_equal 'bar'
# MyClass.all_instances.unstub(:foo, 'bar')

class AllInstances
  def initialize(klass)
    @klass = klass
    @@new_method_names ||= {}
  end

  def stub(method_name, return_value)
    @@new_method_names[method_name] = "_original_#{method_name}".to_sym
    @klass.send(:alias_method, @@new_method_names[method_name], method_name)
    @klass.send(:define_method, method_name, ->(*args){ return_value })
    if block_given?
      begin
        yield
      ensure
        unstub(method_name)
      end
    end
  end

  def unstub(method_name)
    @klass.send(:remove_method, method_name)
    @klass.send(:alias_method, method_name, @@new_method_names[method_name])
    @@new_method_names[method_name] = nil
  end
end

class Class
  def all_instances
    AllInstances.new(self)
  end
end

Cute Ruby trick: split a hash into two hashes with a block

Posted in code, ruby by mtjhax on June 21, 2013
foo = { 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4 }
bar = foo.select {|k, v| foo.delete(k) || true if k >= 'c' }
# foo == {"a"=>1, "b"=>2}
# bar == {"c"=>3, "d"=>4}

So why use || true? Consider this example:

foo = { 'a' => 1, 'b' => 2, 'c' => nil, 'd' => 4 }
bar = foo.select {|k, v| foo.delete(k) if k >= 'c' }
# foo == {"a"=>1, "b"=>2}
# bar == {"d"=>4}

foo.delete(k) returns the value that was deleted, which in the case of key ‘c’ is the value nil. The Hash#select method treats nil as meaning do not select this element for the result set, so the ‘c’ entry is deleted from the original hash and not included in the result hash. Adding || true returns true even if the value in question evaluates to false or nil.

Backboned

Posted in code, javascript by mtjhax on February 26, 2013

Read Backbone’s docs carefully to avoid a fatal security flaw

If you use Backbone.js you are probably “bootstrapping” the data for your models, per their instructions:

Loading Bootstrapped Models
When your app first loads, it’s common to have a set of initial models that you know you’re going to need, in order to render the page. Instead of firing an extra AJAX request to fetch them, a nicer pattern is to have their data already bootstrapped into the page. You can then use reset to populate your collections with the initial data. At DocumentCloud, in the ERB template for the workspace, we do something along these lines:

<script>
  var accounts = new Backbone.Collection;
  accounts.reset(<%= @accounts.to_json %>);
  var projects = new Backbone.Collection;
  projects.reset(<%= @projects.to_json(:collaborators => true) %>);
</script>

 
You have to escape </ within the JSON string, to prevent javascript injection attacks

If you are using Rails 3.x and follow the example code verbatim, you might get something like this in your output:

// var widget = new widgets.model(<%= @widget.to_json %>)
var widget = new widgets.model({ &quot;title&quot; : &quot;&lt;/script&gt;&lt;script&gt;alert('hi')&lt;/script&gt;&quot; });

Obviously, the output is being escaped and .html_safe or raw() needs to be used:

// var widget = new widgets.model(<%= @widget.to_json.html_safe %>)
var widget = new widgets.model({ "title" : "</script><script>alert('hi')</script>" });

Now wait just one second! Some sneaky devil has entered some JavaScript in their title field. You might wonder if this is okay because it’s inside a string — it’s not. If you run this example the alert("hi") code will be executed because the browser’s HTML parser can’t sully itself with understanding JavaScript syntax, so closes the script tag at the very first </script it sees. So by unescaping your output you have created a wide-open security hole exposing your users to XSS attacks.

Maybe you didn’t notice that last line in Bootstrap’s instructions. It’s pretty important.

You have to escape </ within the JSON string, to prevent javascript injection attacks.

I almost fell for this trap before remembering how dangerous html_safe or raw() could be in Rails views, especially in a script section. An old-school trick for breaking up or escaping </script> inside strings is to use "</sc"+"ript>". Ugly hack. There’s an ugly but non-hack way to do it with a CDATA directive. The accepted method, per Backbone’s link, is to simply escape the forward slash character with a backslash: <\/script>.

So you might ask, what is the proper way to do this in Rails? John Firebaugh has a nice writeup of the various alternatives. Some developers have suggested monkeypatching the to_json but this hides the protection from the view and can lead to bad habits. I believe the view code should show explicit evidence of escaping to prevent injection attacks until such escaping becomes a Rails default. Firebaugh ended up suggesting that you replace ActionView::Base#json_escape instead, simply escaping all forward slash characters with blackslashes (gsub('/', '\/')). This is a safe approach because the use of json_escape in views makes the protection explicit.

If you prefer not to overwrite Rails methods to accomplish this task, you could just define a new method such as Object#to_safe_json or ActionView::Base#safe_json. Another way is to use escape_javascript and html_safe together to create a string which is then parsed in JavaScript:

//$.parseJSON('< %= escape_javascript @widget.to_json.html_safe % >')
var widget = new widgets.model($.parseJSON('{\"title\":\"<\/script><script>alert(\'hi\')<\/script>\"}'));

Some developers feel this is inefficient because you have to parse the JSON string, but it makes sense to me — you parse the JSON string returned by every AJAX request, so why not the initial one? This shouldn’t affect your page load performance unless you are bootstrapping a huge Collection, in which case you might want to think about adding some pagination.

Sticky Footers Break Bootstrap ScrollSpy

Posted in bootstrap, code, jquery by mtjhax on February 12, 2013

If you saw my previous post, you know that I am currently playing with the Twitter Bootstrap ScrollSpy plugin. I reviewed their sources (which took a bit of effort as the code was written for compactness, not readability) and got my examples working. When I tried it with a real site, however, everything stopped working. ScrollSpy would only highlight the last element in my nav.

I fired up the debugger on an un-minified bootstrap.js to look at the size and position variables and saw that the value for the maxScroll var was 0. maxScroll holds the difference between the total scrollable height and the actual/visible height (as calculated by jQuery height()). This value should only be 0 if the scrollable content fits entirely in the visible area, yet my content was 1400px in height and the visible height was only around 400.

DOM inspection revealed that the document body had the correct scrollHeight value of 1400, but $('body').height() was 1400 as well. Normally, $('body').height() would return 400, the visible size. I had one of those “what the actual f…” moments for a few seconds.

Light Dawns

The site layout I am using is employing the sticky footer technique, which forces your footer to the bottom of the visible browser window, even when the page is smaller than the window. The relevant CSS is as follows:

* {
  margin: 0;
}
html, body {
  height: 100%;
}
.wrapper {
  min-height: 100%;
  height: auto !important;
  height: 100%;
  margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
  height: 142px; /* .push must be the same height as .footer */
}

/*
Sticky Footer by Ryan Fait
http://ryanfait.com/
*/

Oops. We are explicitly setting the height of body to 100% of the document height, so $('body').height() is no longer just the visible area, but the same as document.body.scrollHeight.

What’s the solution?

It turns out that someone already tried to get a workaround merged into Bootstrap, but they didn’t follow Bootstrap’s procedures for submitting a pull request and were summarily rejected. I’m not sure that fix would work anyway — it uses the sticky footer #wrap div to get a different scrollHeight, but the scrollHeight is not the problem — it’s $scrollElement.height() that is returning the full document height instead of the visible height.

Some options for a fix include:

  • Override the sticky footer styles for the page in question (just use html,body { height: auto }) or use a different stylesheet with the ScrollSpy page. This doesn’t feel right to me. Page-specific conditional styles are the path to the dark side.
  • Skip the sticky footer styles based on some clever CSS that conditionally removes them. This is still a conditional but it seems a bit more expressive and makes the solution all CSS. Imagine an HTML element like <div class="container unstick_footer">. The only problem is that this won’t be possible until CSS4.
  • Stop using sticky footers? Maybe you don’t really need them. A lot of people just add them to every project before they even have a design.
  • Put your scrollable content inside an element that has a fixed height and use ScrollSpy on that instead of the body. This would not work for everyone and makes it a bit more difficult for your scrollable area to adjust to different page heights. You would need some JavaScript and/or Responsive CSS styles to avoid just having a fixed-height box.
  • Submit a patch for Bootstrap that gets the visible height of the body even if some nutcase has defined it to have height 100% of the document height.
  • My favorite (which may not be possible) is to fix the sticky footers CSS so they don’t increase the height of the body beyond the visible window. I may need to call in a CSS ringer to help me with that one.

I’d love to explore all these approaches and compare their pros and cons, but time isn’t my friend. I’d love to hear about your ideas and any approaches that work.

Twitter Bootstrap’s Scrollspy Plugin Needs Better Docs

Posted in Uncategorized by mtjhax on February 11, 2013

I was trying to get Twitter Bootstrap’s Scrollspy plugin working so I can have a nice sidebar-nav menu like theirs that highlights automatically as you scroll the page. I created a JSFiddle here to demonstrate what I am trying to do.

Click here to see the non-working example full-screen

Arrrrrrgh! I thought I followed their instructions to the letter. The tag contains attributes data-spy="scroll" to activate scrollspy and data-target="#my-nav" to indicate which nav I want to highlight to match the scrolled page. After much trial-and-error I removed the data-target attribute and presto:

Click here to see the working example full-screen

This contradicts their documentation, so I poked around Stack Overflow looking for answers and I found many people reporting similar issues and not really getting decent answers. Usually they report that nothing happens with scrollspy or the last entry in the list is highlighted and will not change as you scroll. Some further digging uncovered this issue report on the Bootstrap GitHub page.

As it turns out, the Bootstrap folks are assuming that your nav menu will have a wrapper of some sort, like a div, and that the data-target attribute needs to reference the nav wrapper, not the nav itself:

    <body data-spy="scroll" data-target="#my-nav">
    <!-- WRONG -->
    <div>
      <ul id="my-nav" class="nav nav-list affix">
    <body data-spy="scroll" data-target="#my-nav">
    <!-- CORRECT -->
    <div id="my-nav">
      <ul class="nav nav-list affix">

Click here to see the corrected example full-screen

Apparently, my original example worked when I removed the data-target attribute because it defaults to finding the first nav in the body. The instructions on how to activate scrollspy with JavaScript are very misleading. They suggest:

$('#navbar').scrollspy();

This implies that you should call the scrollspy() method on the nav object, but if you do it, it results in the behavior where the last entry in your nav menu is activated and the menu will not change as you scroll. I thought you needed to target the wrapper, as with the HTML attribute method, but this also does not work. If you use $(document.body).scrollspy() it seems to work, but again this seems to be the code defaulting to use the first nav it finds in the page. Apparently, what I should have done from the start is just read the bootstrap.js source code and figured out what was going on — doing that tomorrow and will post an update.

By the way, the official response to this issue report was “good catch, why don’t you fix the docs and open a pull request” and the issue was closed. When I have time I will see if I can help out and not just complain…

UPDATE: After looking at the code it’s pretty obvious. To initialize ScrollSpy with JavaScript, the scrollspy() method should not be called on the target nav, but on the document body or container being scrolled. The documentation is not entirely clear on how to specify the target, because it assumes a familiarity with some common techniques and conventions. The target nav can be specified as an attribute similar to the way the offset is specified. The lack of explicit documentation is probably another oversight since offset is clearly documented. Example:

// using the not-explicitly-documented 'target' attribute
$('body').scrollspy({ target: '#my-nav' });

Another JSFiddle to prove that it works.

Ruby 1.8 strftime works differently on Linux and Windows

Posted in code, ruby, ruby on rails by mtjhax on December 27, 2010

Running Ruby 1.8 on Linux, cygwin, Mac, any POSIX environment:

now = Time.now
=> Mon Dec 27 18:28:28 -0500 2010
now.strftime("%l") # that's a lowercase "L"
=> " 6"

Under Windows using the exact same Ruby version and patch level:

now = Time.now
=> Mon Dec 27 18:28:28 -0500 2010
now.strftime("%l") # that's a lowercase "L"
=> ""

What? It turns out in Ruby 1.8 they cheated by simply calling the standard C strftime() function to implement Ruby’s strftime method. Because different compilers implement strftime() differently, compiling it under Windows results in a different set of supported % directives. Specifically, it looks like under Windows only the basic ANSI C version is implemented, but under POSIX compilers you get a mix of directives defined by ANSI and other standards like Gnu and Single Unix Specification. The “%l” directive was not even listed in the Ruby 1.8 docs — it worked by accident.

The good news is in Rails 1.9 they appear to have implemented their own strftime for consistency, instead of handing it off to the C compiler. If you need to fix this in the meantime, I provide the following monkey patch (which I simply place in my Rails config/initializers folder on any Windows developer machine):

# monkey patch Ruby strftime methods to implement
# %l directive that is missing in Windows Ruby
#
# as a monkey patch, just use this on your Windows
# development boxes to bridge the gap, it's not
# recommended for production
#
# notes:
# - you may want to add support for other missing directives
# - check your RUBY_PLATFORM and make sure it is in the regexp below
#
if RUBY_PLATFORM =~ /mingw32|mingw64|mswin32|mswin64/

  class Time
    alias_method :original_strftime, :strftime
    def strftime(fmt)
      hour12 = "%2d" % ((hour + 11) % 12 + 1)
      original_strftime(fmt.gsub(/%l/, hour12))
    end
  end
 
  class Date
    alias_method :original_strftime, :strftime
    def strftime(fmt)
      hour12 = "%2d" % ((hour + 11) % 12 + 1)
      original_strftime(fmt.gsub(/%l/, hour12))
    end
  end

end
Tagged with: , ,

Ruby SystemTimer gem for Windows

Posted in code, ruby on rails by mtjhax on December 23, 2010

SystemTimer is a Gem that replaces timeout.rb and fixes some potentially serious flaws when accessing system resources (e.g., when communicating with remote APIs) in Linux/Posix environments. In a nutshell, timeout.rb uses Ruby pseudo-threads (“green threads”) that are not guaranteed to be given the same equal opportunities in the CPU as real system threads, resulting in synchronization problems. Visit http://ph7spot.com/musings/system-timer for all the details.

If you end up needing to use SystemTimer on your production environment and you develop on Windows, you have a problem. SystemTimer’s documentation says that it can be installed under Windows (providing the same interface for your code but not really changing anything — it just acts as a wrapper to timeout.rb). In practice, however, trying to “gem install SystemTimer” results in errors building the native extensions even if you have the RubyInstaller DevKit installed.

Solution? Simple! I don’t know who ghazel is but my hat’s off to them. They took the time to branch the SystemTimer project, patch it to install under Windows and simply provide the wrapper classes without trying to compile anything, and put it up on RubyGems.org.

Visit http://rubygems.org/gems/ghazel-SystemTimer or just “gem install ghazel-SystemTimer” and you should be good to go on your Windows development box in about two seconds.

Action and reaction: event-driven AJAX updates with jQuery

Posted in code, jquery by mtjhax on September 7, 2010

Newton's CradleAs I increasingly use AJAX to let users perform actions in a page without navigating away, I find myself constantly having to solve the problem of updating page content that depends on these actions. For example, a user logs in with a popup bubble, then parts of the page that depend on login state must be updated. This is a relatively trivial example and there are many approaches to handling this sort of update.

A straightforward method that is commonly used is to avoid AJAX in these cases–submit the login form and redirect back to refresh the entire page. While using AJAX sparingly is a worthwhile goal, avoiding it entirely doesn’t always result in the most engaging user experience. Another approach is to hard-code everything that needs to be updated after an action is complete:

// submit my login form with jQuery .ajax()
$.ajax({ url: login_url, data: login_data, complete: function() {
  // update page contents that depend on login state
  $('#mainmenu').load('mainmenu');
  $('#login_form').fadeOut('slow', function() {$(this).remove()});
  $('.welcome_text').show();
});

Fine for one or two actions, but this turns into a spaghetti mess pretty quickly in more complicated situations. A better solution is to have some way of registering update callbacks, e.g.:

$('#mainmenu').updateOnEvents('login', function() {
  $(this).load('mainmenu');
});

$('#login_form').updateOnEvents('login', function() {
  $(this).fadeOut('slow', function() {$(this).remove()});
});

$('.welcome_text').updateOnEvents('login', function(){
  $(this).show();
});

$.ajax({ url: login_url, data: login_data, complete: function() {
  // globally trigger the event 'login' somehow
});

So the question becomes, how do you globally trigger the event so any element at any level can register a handler? After considering a number of designs involving .live() or .delegate() (so the handler setups would affect both existing elements and new elements added later) I realized that good old .bind() would do the trick.

Solutions involving .live() and .delegate() are tricky because when you use something like $('.foo').live() or $(document).delegate('.foo'), you need to use $('.foo').trigger() for the event to be handled. Calling something higher-level like $(document).trigger() does not invoke the handlers. The trick is to roll your simple .live()-style function similar to the following:

$.fn.updateOnEvents = function(events, callback) {
  $(document).bind(
    events,
    { selector: $(this).selector, context: $(this).context },
    function(event, trigger_data) {
      $(event.data.selector, event.data.context).each(function(){
        if (typeof callback == 'function') {
          extra_data = callback(event, trigger_data);
        }
      });
    }
  );
};

// example usage
$(document).ready(function() {
  $('.welcome_text').updateOnEvents('login logout', function(event, data){
    $(this).text(data.message).show();
  });

  $(document).trigger('login', { message: "Welcome back!" });
  $(document).trigger('logout', { message: "See you next time." });
});

The trick is that when we call $('.foo').updateOnEvent(), the selector string ‘.foo’ is saved (and the context, if specified) and are passed to the handler function in event.data. The handler uses the selector and invokes the callback function for each matching element with .each(), so the value of $(this) in your callback is the element itself instead of $(document). Since the selector is evaluated at the time of the callback, any recently-added elements that match are included in the update.

The parameter trigger_data is whatever extra data you pass with the .trigger() call and your callback can take advantage of that data.

Commonly-used patterns can be expressed as a shortcut in the code. For example, in this variant if the callback parameter is a string instead of a function, the code treats the string as an AJAX URL and assumes you want to update the selected elements with .load():

$.fn.updateOnEvents = function(events, callback) {
  $(document).bind(
    events,
    { selector: $(this).selector, context: $(this).context },
    function(event, trigger_data) {
      if (typeof callback == 'function') {
        $(event.data.selector, event.data.context).each(function(){
          extra_data = callback(event, trigger_data);
        });
      } else if (typeof callback == 'string') {
        $(event.data.selector, event.data.context).load(callback, trigger_data);
        });
      }
    }
  );
};

// slightly absurd example of using AJAX to retrieve a welcome message
$(document).ready(function() {
  $('.welcome_text').updateOnEvents('login logout', '/ajax/welcome_msg');
  $(document).trigger('login', { type: "login" });
  $(document).trigger('logout', { type: "logout" });
});

In yet another variant where I always want to update the element with AJAX via .load(), instead of passing a callback function to perform the updates, I passed a callback function that returns the parameters for the .load() call — in this way, the .trigger() function doesn’t need to know anything about the parameters needed by the update callbacks:

$.fn.updateOnEvents = function(events, ajax_url, params_callback) {
  $(document).bind(
    events,
    { selector: $(this).selector, context: $(this).context, url: ajax_url },
    function(event) {
      var data = extra_data;
      $(event.data.selector, event.data.context).each(function(){
        // get AJAX request parameters from callback function
        if (typeof params_callback == 'function') {
          data = params_callback(event);
        }
        // convert params to string so .load() always uses GET method
        if (typeof data == 'object') {
          var new_params = "";
          for (var key in data) {
            if (new_params.length > 0) new_params += "&";
            new_params += key + "=" + data[key];
          }
          data = new_params;
        }
        // update the element with AJAX
        $(this).load(e.data.ajax_url, data);
      });
    }
  );
};

// another slightly ludicrous usage example
$(document).ready(function() {
  $('.welcome_text').updateOnEvents('login logout', '/ajax/welcome_msg', function(event){
    if (event.type == 'login')
      return { type: "login" };
    else
      return { type: "logout" };
  });
});

I have to profess that I am not a jQuery god (yet). I am certain that there are improvements that could be made to this function in terms of performance and simplicity, maybe a potential error or two, or a completely better way to approach the problem. I welcome your suggestions, comments, and criticism!

Tagged with: , , , , ,

jQuery fadeIn / fadeOut problem in IE

Posted in code, jquery by mtjhax on May 7, 2010

Say you have a series of DIVs displayed side-by-side with the CSS style display:inline, and you want to use jQuery fadeIn and fadeOut to make the appear and disappear. This will not work under IE8, and I assume other versions of IE. To fix it, give your elements style="display:inline-block" instead.

Some people have reported that using absolute and relative positioning of elements causes jQuery animation problems in IE, but I have yet to see positioning cause any problems. I very commonly use a position:relative DIV, then position:absolute elements within the DIV (probably rely on it too much, never claimed to be a CSS designer!)

UPDATE:

I ran into a similar problem under IE8 where a DIV could be hidden and displayed with jQuery .hide() and .show(), and .fadeOut() and .slideUp() would work, but .fadeIn() and .slideDown() would not work at all. The HTML looked something like this:

<div id="page_help">
<div id="help_toggle">Click here to hide help</div>
<div
id="help_text">This is some help text</div>
</div>

I had a CSS definition for the help_toggle class setting it to display:inline-block and the fadeIn/slideDown problems started appearing in IE8.  When I set it to display:block the problem went away. Bizarrely, if I inserted an HTML comment between the help_toggle and help_text DIVs, the problem also went away! E.g.:

<div id="page_help">
<div id="help_toggle">Click here to hide help</div>
<!-- bizarrely enough, this fixes the jquery fadein problem -->
<div
id="help_text">This is some help text</div>
</div>

This is baffling. The only moral to the story I can figure out is that jQuery animations do not appreciate block and inline elements being siblings, and sometimes setting inline-block as the display style is not sufficient to get things working again.

Rails named_scope gotchas

Posted in ruby on rails by mtjhax on April 29, 2010

There are two terrible gotchas in Rails named_scopes. These two have bitten many a named_scope newbie on the rear (including myself, except that my unit tests caught the problems before they went anywhere but my desktop, w00t for TDD!)

#1. Use length instead of size with the results returned by named_scopes.

Under certain conditions, particularly when using :limit in a named_scope, size and length will return different values. Example:

class Book < ActiveRecord::Base
  named_scope :top, lambda { |limit| {
    :limit => limit,
    :order => 'total_sales DESC'
    }}
end
# imagine we have 10 books with various values for total_sales...
>> Book.top(5).length
=> 5
>> Book.top(5).size
=> 10
# for some reason this only affects named_scopes:
>> Book.find(:all, :limit => 5).length
=> 5
>> Book.find(:all, :limit => 5).size
=> 5
# Go figure!

#2. named_scopes and AR calculations don’t mix

Named scopes are a joy to use, especially when you chain them. It’s completely addictive being able to use constructs like:

topten = Book.fiction.category('vampire').top(10)

(Hypothetical example, I do not read vampire novels…).

The arrays returned by named_scope are ActiveRecord arrays and support calculations such as .count and .maximum, so it’s tempting to want to try something like:

max_fiction_price = Book.top(10).maximum(:price)

Beware! You may not get the results you are looking for — in my experience, these will not work consistently. The problem is that ActiveRecord generates a query something like the following:

SELECT MAX(price) from books ORDER BY price DESC LIMIT 10;

As far as I can tell in researching it, this is not really valid SQL (at least not according to MySQL). LIMIT happens after everything else–similar to HAVING–and only filters the number of output rows that are displayed. Since the MAX() function tells SQL to aggregate the results into a single column, the ORDER and LIMIT clauses are meaningless.

Sometimes this type of statement works for me. I have tried it on SQLite3 and several different versions of MySQL for Linux and Windows. The database sometimes seems to understand that I want to order by price, take the top 10, then calculate the max price. It is entirely possible that in tests where the result appears to be correct, it is actually because the records were randomly ordered in a way that produced the correct result, but purely by chance.

Of course, Rails 3.0 is on the way and there may end up being changes in these behaviors since AR is being rebuilt from the ground up. Whatever the case, avoid mixing conditions and limits, and make sure your unit and functional tests are written to validate the number of results your named_scopes return.