Making CanCan RSpec ability tests DRY May 3

When testing permission sets using CanCan and RSpec, you might find that you end up using the same context descriptions and/or let statements. For example:

describe User, "abilities" do
  subject(:ability) { Ability.new(user) }
  
  describe "widgets" do
    context "when user" do
      let(:user) { create(:user) }

      it { should be_able_to(:create, Widget) }
    end
  end

  describe "gears" do
    context "when user" do
      let(:user) { create(:user) }

      it { should be_able_to(:create, Gear) }
    end
  end
end

Continue Reading...

Testing CanCan in your controllers with RSpec and Mocha Feb 7

CanCan is one of my favorite Rails gems, allowing you to easily define user permissions on your app’s resources. CanCan also makes it very easy to test these permissions using its built-in RSpec matchers. Once these permissions have been defined, a before filter is used in the controller to make sure the user can access a resource. CanCan unfortunately doesn't provide any way to easily test the controller implementation.

Testing specific permissions at the controller or request level would defeat the simplicity of CanCan and make changing your permission system more difficult (especially if it’s complex), but you do want to make sure that CanCan is doing its job enforcing the permissions. So what's the solution? Simple: make sure CanCan's authorize! method is getting called on the right actions and with the right arguments.

Continue Reading...

Using RSpec's format_docstrings to format and tag your tests Feb 2

One of the nice things about RSpec’s DSL is that it allows you to describe your tests using as long (or as short) of a description as you want. In cases where a short description isn’t going to cut it, you’ll probably end up inserting line breaks in the description like this:

it %(does thing one, thing two, thing three, thing four
  thing five, thing six, etc... under these conditions...) do
  # ...
end

The problem occurs when using the documentation formatter or any other formatter that outputs test descriptions:

bundle exec rspec spec/ --format documentation

Continue Reading...