How to Write Rspec Mailer Tests

| Comments

The last few weeks have been a whirl-wind of building, which has been so wonderful. I really feel like I got to flex my muscles a little bit (I learned to encrypt things..post to come later) but the other side of building is testing. I built three different mailers, and then learned that you can actually test your mailers with rspec. And it’s not that difficult!

I chose a few very basic pieces of mailer functionality to test:
1. Was it actually sending the email
2. Was the email being sent to the desired recipient
3. Was the subject line of the email correct
4. Was the email being sent from the correct address

This was also really helpful because up until this week, we’ve only been able to test mailers locally. These Rspec tests were essentially the only way I was able to tell if the mailers were functioning how I wanted them to function.

So here was my mailer method:

def confirmation_email(ordered_story)
  mail(to: story.email, subject: "Here Is Your Story!", content_type: "text/html")
end

In my mailer spec, the first thing I did was set up a few configurations for ActionMailer that I declared to happened before each test.

  before(:each) do
    ActionMailer::Base.delivery_method = :test
    ActionMailer::Base.perform_deliveries = true
    ActionMailer::Base.deliveries = []
    @story = Factory.create(:story)
    EbookConfirmationMailer.confirmation_email(@story).deliver
  end

I’m basically saying: send my emails in the testing environment (which does have to be explicitly declared), please actually perform all my deliveries, create an array of all my sent emails, build the factory for my story class (with an instance of that class), and then finally deliver my email.

Then, I wanted to clear all of that after each test so I have a clean slate before each test.

after(:each) do
  ActionMailer::Base.deliveries.clear
end

So now that I have all of that set up, the tests.

1. Is the email being sent?

  it 'should send an email' do
    ActionMailer::Base.deliveries.count.should == 1
  end

I had originally set up my array of delivered emails, so in this test, there should only be one email. My before statement only called one email to be delivered.

2. Is the email being sent to the desired recipient?

  it 'renders the receiver email' do
    ActionMailer::Base.deliveries.first.to.should == @story.email
  end

The Story class, has an email attribute, which is what is declared as the to: in my mailer method. The Story Factory builds an instance of the class with an email address which is the one that should be used to send the email (@story.email).

3. Does the email have the correct subject line?

  it 'should set the subject to the correct subject' do
    ActionMailer::Base.deliveries.first.subject.should == 'Here Is Your Story!'
  end

The subject line of the email was expplicitly defined in my mailer. So if my email is sending properly, that subject line should be rendered in the email.

4. Was the email being sent from the correct addres?

  it 'renders the sender email' do  
    ActionMailer::Base.deliveries.first.from.should == ['notifications@stories.com']
  end

When I defined my mailer, I defined a default from address default :from => "notifications@stories.com" So just like the subject line, if the email is being sent properly, that should be the from address, plain and simple.

I guess the next step with these will be testing the mailer views (I also recently learned that you can write tests for views! Cool!)..so clearly I have lots more blog posts to write.

5 Things I Learned About Encryption

| Comments

So I was recently asked to encrypt an id, and then somehow take that encryption and display it as part of a URL. Essentially, it was a mock form of security for a new feature at work, so that a user couldn’t just change an id in a url and move around things that should remain private.

_Encryption is an entirely new concept to me.__ I didn’t even know what it really meant. So it was a really big learning exercise for me. Ps. Encryption means to convert data into cipher. Oh and cipher is “diguised way of writing code” (thanks Google ).

1. Ruby has an OpenSSL library used for encryption. This library has greate documention here

How–and when–To Use a Struct

| Comments

Recently I’ve been going through my ever growing (and then shrinking, and then growing again) list of new things/situations I’ve been introduced to via my code base at work. Which lead me to dig a little deeper into Ruby structs.

A struct is a simple way to bundle attributes together without having to explicitly define a class, all the while giving you accessor methods for those attributes. You can read the Ruby Docs about structs here.

We’ll use the example of creating people.

A struct can be created very easily in two different ways:

  Struct.new("Person", :name, :age, :address)
  Person = Struct.new(:name, :age, :address)

So now we have our Person struct, Struct::Person. This gives us really easy accessor methods for all three attributes of the struct that we defined.

We can easily create new instances of this struct:

  Struct::Person.new("Victoria", 24, "1835 University Circle")
  victoria = Person.new("Victoria", 24, "1835 University Circle")

So how do we access the attribtues of this new instance of the struct?

  victoria["name"] #=> "Victoria"
  victoria["age"] #=> 24
  victoria["address"] #=> "1835 University Circle"

You can also change the values of an instance of the struct:

  victoria["name"] = "Vic"
  victoria["name"] #=> "Vic"

So what’s the difference between Struct and OpenStruct? OpenStruct doesn’t require explicitly defined attributes. You can create them on the fly.

person = OpenStruct.new
person.name = "Victoria"
person.age = 24
person.date_of_birth = "June 1, 1988"

Notice when we created the OpenStruct, we didn’t define any attribute fields, just the name.

Both Struct and OpenStruct closely resemble a hash, so why not just use that? You should think of a Struct as a convience class when you just want to store attributes and read/write to them with regular methods. A hash is a possibility, but a hash isn’t fixed. There can be an infinite and varying number of key-value pairs. A Struct is the way to go when modeling out more complex objects with a known set of attributes.

How to Use State Machine

| Comments

A few weeks ago, I was introduced to an incredible gem called State Machine (you can read their docs here). The gem keeps track of the status of a specific object and respeonds to different inputs to alter that state. The example that I’ve understood the most is in purchasing something (I’m going to use a pack of gum in this post).

The gem breaks down into four different parts:

  1. State- the status of the object. All states are predefined in the class. All objects start in the initial state. The first step to buying a pack of gum is to select it. So the pack of gum would move from initial to selected.

  2. Transition- the movement from one state to another. A pack of gum would transition from the initial state to the selected, and then again transition to the queued state when the user is in line to purchase it.

  3. Event- The invocation of a state. A pack of gum would transition from the initial state to the selected, by way of an event. Another event would trigger the queued state.

  4. Action- State Machine can trigger different methods before, during, and after transitions.

So let’s further elaborate on this example of buying a pack of gum.

What states would there be?

  • Selected - I deciced I want zebra gum, so now I’m holding it
  • Queued - waiting in line to purchase
  • Purchased - handing money to cashier
  • Owned - I own and can do whatever I want with the gum
  • Trash- After I chew the gum, it’s garbage
  • Here is an example of a class set up with State Machine, and then I’ll go through and explain each step.

      class Gum
        attr_accessor :flavor, :price, :state
    
        state_machine :initial => :selected do
    
          before_transition :on => purchased :do => :demand_money
          after_transition :on => owned, :do => :be_chewed
    
    
          event :queue do
            transition :selected  => :queued_for_purchasing
          end
    
          event :purchase
            transition :queued_for_purchasing => :purchased
          end
    
          event :ownership
            transition :purchased => :owned
          end
    
          event :trash do
            transition :owned => :trash
          end
    
    
          state :queued do
            def is_queued?
              return true
            end
          end
    
          state :purchased do
            def is_purchased?
              return true
            end
          end
    
          state :owned do
            def is_owned?
              return true
            end
          end
    
          state :trash do
            validate { |gum| gum.trash? }
            def is_trash?
              return true
            end
          end
    
        end
    
        def demand_money
          #demand money here
        end
    
        def be_chewed
          # method to prepare piece of gum to be chewed
        end
    
    
      end
    

    So how does this work?

    State Machine first gets included in your Gemfile.

    From there, the set up is all done from inside the class where the objects change states. All objects start in the initial state, which is defined with when State Machine is invoked:

      state_machine :initial => :selected do
    

    Next, the states must be defined:

      state :queued do
        def is_queued?
          return true
        end
      end
    
      state :purchased do
        def is_purchased?
          return true
        end
      end
    
      state :owned do
        def is_owned?
          return true
        end
      end
    
      state :trash do
        validate { |gum| gum.trash? }
        def is_trash?
          return true
        end
      end
    

    Following, the events must be defined:

      event :queue do
        transition :selected  => :queued_for_purchasing
      end
    
      event :purchase
        transition :queued_for_purchasing => :purchased
      end
    
      event :ownership
        transition :purchased => :owned
      end
    
      event :trash do
        transition :owned => :trash
      end
    

    Here, the events specify transitions between states. These events can be triggered in the command line as well, which would trigger new states. The state is saved as an attribute of an instance of the class.

    Then, the actions to be called must be defined:

       def demand_money
          #demand money here
        end
    
      def be_chewed
        # method to prepare piece of gum to be chewed
      end
    

    Finally, the actions must know to be called during transitions:

      before_transition :on => purchased :do => :demand_money
      after_transition :on => owned, :do => :be_chewed
    

    So, to test the flow of all of this in command line, there is a handy method fire_events. That method looks like this:

      gum = Gum.first
      gum.state #=> selected
      gum.fire_events(:queue) #this transitions the gum from selected to queued_for_purchase
      gum.state #=> queued_for_purchase
    

    The only thing to know is that you cannot rollback states through triggering events. You can however explictitely redefine the state (gum.state = "selected") and from there retrigger the events.

    Enjoy!

    An Introduction to Say_with_time

    | Comments

    I don’t think I will ever know everything about Rails. And that’s part of its magic, every day there is something that makes me go “Woah, cool!”

    Meet, say_with_time, a really handy little method used in migrations to create a more readable output. This is especially useful when your migrations are doing more than one simple task. I’ve seen it used during a migration that loads a yaml file. What? I didn’t even know you could do that.

    say_with_time is a method called directly in the body of a migration during the up, down or change methods. You must pass a block to the method, which controls the entire migration.

      def up
        say_with_time "adding columns email and deleted_at to profiles" do
          add_column :profiles, :email 
          add_column :profiles, :deleted_at
        end
      end
    
      def down
        say_with_time "removing columns email and deleted_at from profiles"
          remove_column :profiles, :email
          remove_column :profiles, :email
        end
      end
    

    The output of running the migration will include the entire quote as well as a benchmark for when the migration was complete.

    Easy and efficient way to control your output from migrations.

    How to Use Git With SVN

    | Comments

    My first three weeks at work have been a whirlwind of new information. And even though I am now fully able to contribute and build, I still have a running list of things to research and learn and fully comprehend. One of those things goes back to day one when I was cloning the repositories. “We use SVN repositories” I was told.

    So SVN and Git are the same thing, only different. SVN is an open source version control system, developed by Apache. Git is also an open source version control system, only developed by Linus Torvalds for the development of the Linux Kernel. While they have the same purpose, there are a few subtle differences in how the respositories work.

    A SVN repository doesn’t have strict configuration requirements like a git repository. In fact, you can even have multiple projects in the same repository. Because git keeps track of a full history of all branches in a repository, multiple projects in one isn’t the best idea.

    Another subtle difference is that the main branch in SVN is called trunk. You use the commands svn copy and svn merge to work on feature branches and merge them back to trunk.

    At first I wondered if I needed to learn how SVN works. But then came the question, “Do you use SVN or git?” Once I replied that I use git, I was told I could still use it locally. Wonderful. I just needed to know the basic SVN commands to clone the repositories, and a few things about committing changes.

    So Git and SVN can work together. How? Git has a bridge to svn, using the command git svn. This command prefaces everything.

    When I cloned my work repository, the command began with git svn clone, which clones my remote SVN repository into a local git repository. So from there I am in a local git environment. All my git commands for creating new branches, merging that branch to master, etc. all work!

    So then the moment came when I finally contributed something to the code to commit. Now what?
    1. I do my usual: git commit -m "<my commit message>" <file_name_to_commit>
    2. Then you have to commit with svn, so it’s actually committed to the SVN repository: git svn dcommit

    And really that’s it. Easy as pie.

    Total side note, but I learned about git stash and git stash apply and wanted to share that tidbit. git stash allows you to stash away half-finished work, commit finished work, and then return to it later with git stash apply. You can read more about it here.

    Great Resources:
    1. https://help.github.com/articles/what-are-the-differences-between-svn-and-git
    2. http://git-scm.com/book/ch8-1.html
    3. http://blogs.wandisco.com/2011/10/24/subversion-best-practices-repository-structure/

    How to Use ActiveResource (and How It Works for You)

    | Comments

    ActiveResource provides an interface for communication between Rails applications. I came across ActiveResource in my databaseless classes at work that I mentioned in my previous post. Essentially, all of our user functionality (logging in, creating a profile with attributes, etc.) is handled by one application and the meat of the site by another.

    And this is where ActiveResource comes in handly. In the simplest of terms, ActiveResource::Base is the main class, which maps RESTful resources as models in a rails application. This boils down to your RESTful resources becoming mutable Ruby objects. ActiveResource acts just like ActiveRecord, so it’s very easy to understand at a first look. The only difference is that ActiveResource deals with HTTP resources that are built on standard JSON or XML request formatting as opposed to dealing with a database. In fact, if I hadn’t noticed the: class Profile < ActiveResource::Base, I might have thought I was dealing with ActiveRecord objects.

    So let’s take the example of this Profile class.

    The first step is to create a model class (one that does not have a migration) that inherits from ActiveResource::Base and that provides a site class variable.

    class Profile < ActiveResource::Base 
      self.site = "http://api/profiles:3000"
    end
    

    My Profile class will be using ActiveResource to talk back and forth with "http://api/profiles:3000"

    Object manipulation in ActiveResource uses standard RESTful requests:
    1. GET requests for finding and retrieving resources
    2. POST requests for creating new resources
    3. PUT requests for updating resources
    4. DELETE requests for destroying resources

    Creating an object will come from sending a POST request to the api. Using methods available to ActiveResource, this will look like:

      Victoria = Person.new(:first_name => "Victoria")
    

    Looks a lot like ActiveResource huh? So what is ActiveResource actually doing here?

      POST http://api/profiles/localhost:3000/profiles.json
    

    It’s sending a POST` request to the JSON of the profiles application. The body of the request looks something like this:

      {"Profile": {"first_name": "Victoria", "last_name": "Friedman"} }
    

    The response you should get back is a 201 HTTP status code, which means the request has been fulfilled, as well as notification that your Ruby object was created.

    So now that we have an instance of my Profile class, how about we try and retrieve it. Finding an object with ActiveResource uses a GET request. With ActiveResource methods, this looks like:

      Victoria = Profile.find(1)
    

    Again, the exact same thing as ActiveRecord. So how does this GET request come into play? A GET request is sent to http://api/profiles:3000/profiles/1.json. That’s the JSON to Victoria Friedman’s profile. Each JSON element becomes an attribute of an instance of my Profile class. I can also find all people by calling:

      profiles = Profile.all
    

    This will return an array of JSON that looks something like this:

      [ {"id": 1, "first_name": "Victoria", "last_name": "Friedman"},
        {"id": 2, "first_name": "Megan", "last_name": "Smith"},
        {"id": 3, "first_name": "Catherine", "last_name": "Brooks"},
      ]
    

    So now we want to update an instance of our Profile class. This works the same in ActiveResource as ActiveRecord but uses a PUT request:

      Victoria = Profile.find(1)
      Victoria.first_name => 'Victoria'
      Victoria.first_name = 'Vic'
      Victoria.save
    

    Now my name is saved as Vic. This submits a PUT request with a body that looks like this:

      {"person": {"first_name": "Vic"}}
    

    This request returns an empty response with a 204 HTTP status code.

    So lastly, let’s delete a resource. ActiveResource sends a DELETE request to the api.

      Vic = Person.find(1)
      Vic.destroy
      Vic.exists? => false
    

    This DELETE request sends an empty 200 HTTP status code as response.

    And voila, ActiveResource!

    Resources:
    1. http://apidock.com/rails/ActiveResource/Base
    2. http://railscasts.com/episodes/94-activeresource-basics

    How to Use ActiveModel::Callbacks

    | Comments

    My first big task at work has been to fix all the broken tests in our test suite. It’s actually a great assignment. I’ll learn all the intricacies and relationships of the code, without the risk of breaking something major…the tests are already broken.

    While reviewing one of the model specs today, I came across something that I was not familiar with: ActiveModel::Callbacks

    A callback is a method that acts as a hook into the life cycle of an object. Callbacks allow you to trigger logic before or after the alteration of an ActiveRecord object.

    ActiveModel callbacks are an interface for any class to have ActiveRecord-like callbacks, used especially in the case of databaseless models. In this Rails Cast, Ryan Bates gives a great intro to ActiveModel and how to get it up and running in your app. In the example of my code, we are just using the callbacks module. ActiveModel also provides a bunch of other modules, including but not limited to: naming, serialization, validations, etc. You can find the entire list here.

    The first step to use any of the modules is to include or extend the module in your class. See my previous post for an explanation on the difference between those options to mix in a modules functionality.

      class Pet
        extend ActiveModel::Callbacks
      end
    

    Here, I chose to extend the module because I want the methods to become class methods.

    The next step is to define a list of methods to which you would like to attach the callbacks:

      class Pet
        extend ActiveModel::Callbacks
    
        define_model_callbacks :create, :destroy, :update
      end
    

    For example purposes, I chose to include three common callbacks. Once you defined the methods that are attached to callbacks, they now have access to all three standard callbacks before, after, and around. To take create as an example, I now have before_create, after_create, and around_create accessible to me.

    The next thing is to actually define the create, destroy, and update methods.

      class Pet
        extend ActiveModel::Callbacks
    
        define_model_callbacks :create, :destroy, :update
    
        def create
          _run_create_callbacks do
            ##CODE TO EXECUTE HERE
          end
        end
    
    
        def update
          _run_update_callbacks do
            ##CODE TO EXECUTE HERE
          end
        end
    
    
        def destroy
          _run_destroy_callbacks do
            ##CODE TO EXECUTE HERE
          end
        end
    
      end
    

    You can also shorthand this:

    def create; _run_create_callback { #CODE_HERE }; end
    def update; _run_update_callback { #CODE_HERE }; end
    def destroy; _run_destroy_callback { #CODE_HERE }; end
    

    And finally, now you can use your callbacks!

      class MyClass
        extend ActiveModel::Callbacks
    
        define_model_callbacks :create, :destroy, :update
    
        before_update :my_method
    
        def create
          _run_create_callbacks do
            ##CODE TO EXECUTE HERE
          end
        end
    
    
        def update
          _run_update_callbacks do
            ##CODE TO EXECUTE HERE
          end
        end
    
    
        def destroy
          _run_destroy_callbacks do
            ##CODE TO EXECUTE HERE
          end
        end
    
        def my_method
          puts "This is my method"
        end
    
      end
    

    I have used mine here, so before any instance of MyClass is updated, my_method is run, which will just print the string “This is my method”.

    Also, in playing around, I discovered that you can literally name your callbacks whatever you want. I tried with fun, which would look something like this:

      class Pet
        extend ActiveModel::Callbacks
    
        define_model_callbacks :fun
    
        before_fun :my_method
    
        def fun
          _run_fun_callbacks do
            ##CODE TO EXECUTE HERE
          end
        end
    
        def my_method
          puts "This is my method"
        end
    
      end
    

    The possibilities are ENDLESS. Literally.

      Great Resources:
    1. http://api.rubyonrails.org/classes/ActiveModel/Callbacks.html
    2. http://jeffgardner.org/2011/05/26/adding-activerecord-style-callbacks-to-activeresource-models/
    3. http://railscasts.com/episodes/219-active-model

    Sql Indexes

    | Comments

    In my last post, I mentioned that unique is a reserved word in SQL because of indexes. But to be totally honest, that was the first time I’d even heard of indexes. So I did some more research…and they’re actually pretty cool.

    Basically, an index is a special lookup for tables in a database that are used to speed up data retrieval, aka quicker queries using WHERE and SELECT clauses. In even simpler terms, it’s a pointer to specific data. Only downside is that it slows down data inputs with UPDATE and INSERT clauses. Also, indexes can be created or dropped easily, and will have no effect on the code.

    So first things first, you want to create an index. This process is incredibly simple:

      CREATE INDEX index_name
      on table_name (column_name);
    

    For example, I have a recipes table, and that table has the columns name, ingredients, and preparations. And say you want to be able to easily query for recipes with a specific ingredient, this would be a great time to use an index.

      CREATE INDEX recipe_ingredients
      on recipes (ingredients);
    

    Super easy.

    Now, there are a few different kinds of indexes:

    1. Unique Index: allows no duplicate values to be inserted in the selected column in your table.

      CREATE UNIQUE INDEX recipe_ingredients
      on recipes (ingredients);
    

    It’s simple to create a unique index, but there is an appropriate moment to use it. The above example is the proper way to create a unique index, but not it’s proper use. You wouldn’t be able to include butter in more than one recipe. Or salt. Or hot sauce. Not ok.

    2. Composite Index: used on two or more columns in a table.

    CREATE INDEX recipes
    on recipes (ingredients, preparations);
    

    This index will allow speedy retrieval of data in both the ingredients column and the preparations column.

    3. Implicit Index: this is an implied index, that is automatically created with the formation of a PRIMARY_KEY column, or UNIQUE_KEY column. Any time your table has an ID column, you have an implicit index on that column.

    Obviously, you need to know how to get rid of an index. It’s also really simple and will not affect your data in any way.

      DROP INDEX index_name;
      DROP INDEX recipes;
      DROP INDEX recipe_ingredients;
    

    Now we got rid of all the indexes (except the implicit index) on my recipes table.

    So of course Rails has built in methods with ActiveRecord to deal with indexes. The declaration for indexes in rails is included in your migrations, but the methods must become class methods….

    add_index :table_name, :column_names, options
    

    Your options include :name, :unique, and :order

    So to take my same example of my recipes table from before and the migration AddIndexesToRecipes:

      def self.up
        add_index :recipes, ingredients, :name => 'recipe_ingredients'
      end  
    

    In this example, I created an index on my recipes table, on the ingredients column, and I named the index “recipe_ingredients”. If I had used :unique, I would have created the same problem as before, where my cookies could have butter, but my cake couldn’t. No thanks.

    Rails also makes it really simple to remove indexes, and there are two ways to do so:

    1. Remove an index by column name: remove_index (table_name, column: column_name) remove_index (recipes, column: ingredients)

    2. Remove an index by index name: remove_index (table_name, name: index_name) remove_index (recipes, name: recipe_ingredients)

      Helpful Resources:
    1. http://www.tutorialspoint.com/sql/sql-indexes.htm
    2. http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

    Sql Has Its Moments

    | Comments

    Today I learned, among a million other things, that I will never escape SQL statements. I think I’ve finally faced it. During week 6 at The Flatiron School, when the magic of Rails and ActiveRecord was introduced, my entire class celebrated the fact SQL statements were abstracted away. We could write RUBY and still retrieve the same data, AUTOMAGICALLY. But let’s face it… SQL will always be around.

    What do you do when you have a huge app running with over 100 instances, a mega-goliath database with more migrations and data entries than I’ve ever seen, and on top of those daunting figures, project managers wanting specific data for metrics.You use a SQL GUI and you write SQL statements.

    So this is how I came across a really interesting discovery. Well two actually: SQL has count and distinct keywords available with which to write queries.

    Here is an example of a table I was working on. This table is called photos:

    I was told to write SQL queries to find the number of photos that have been uploaded by users in the last three weeks (so from after June 6), as well as the number of users that have updated photos.

    1. Number of photos uploaded by users on or after June 6, 2013:

    select count(id) from photos where user_id is not null and created_at >= 6/6/2013

    This command is parsing through the data in our database, finding all instances where a user_id is present (in this case all of them), as well as parsing through the created_at dates to find a match and returning to us that number of photos. This command should return five, as there are five photos uploaded by users in the sample database.

    2. Number of users who have uploaded photos on or after June 6, 2013:

    The next query was a little bit more challengeing because I was unaware of the SQL distinct method.

    Originally, I had:

    select count(profile_id) from photos where profile_id is not null and created_at >= 6/6/2013

    But this query returns five.The problem with this query wasn’t immediately obvious to me. Count doesn’t discrimate against repeated entries. There are FIVE cells with a user_id, just not five unique id’s.

    My first thought was the uniq method. Like when you have an array that contains duplicates, you can call uniq on that array to return that array with the duplicates removed. But unique is a reserved word in SQL, and is used to create unique indexes (an index can be created in a table to find data more easily and efficiently). So that’s when I was introduced to distinct.

    With that new knowledge, I was able to correct my first attempt at the query,

    select count(distinct user_id) from photos where user_id is not null and created_a >= 6/6/2013

    And that statement returns the correct result, which is three.