Tag: testing

Testing Sinatra application methods in isolation with RSpec

Sometimes you may want to test some Sinatra app methods in isolation (outside of a standard request flow). You probably even tried to do something like this:

require 'spec_helper'

describe App do
  subject { App.new }

  it 'expect run some specs here'
    expect(subject.current_user).to eq user
  end
end

Unfortunately you will end up with error like this:

NoMethodError: undefined method `current_user' for #<App app_file="/home/something/app.rb">
from (irb):2
from /home/.rvm/rubies/ruby-2.1.2/bin/irb:11:in `<main>'

This will occur, because Sinatra's App new method creates a Sinatra::Wrapper, not an App instance. Of course everything will work as it should, if you follow the get/post/put/delete way of testing Sinatra apps:

require 'spec_helper'

describe App do
  before { get '/api/v1/credit_cards.json' }
    
  it { expect(last_response).to be_ok }
end

but it will fail when trying to invoke any App methods directly.

Luckily there's a really simple solution to this issue. You just need to initialize it by manually allocating space and "bypassing" the new method:

require 'spec_helper'

describe App do
  subject do
    app = described_class.allocate
    app.send :initialize
    app
  end

  describe '#current_user' do
    before do
      expect(subject)
        .to receive(:params)
        .and_return(params)
        .at_least(:once)
    end

    context 'when there is no user_id' do
      let(:params) { {} }

      it { expect(subject.send :current_user).to be_nil }
    end
  end
end

That way you can get the "real" app instance (not a wrapper) that you can use as a subject in your specs. That way you can test your Sinatra app methods in isolation - without having to call a full request.

Ruby programmers/project managers/CEOs Y U NO enforce code quality?

Introduction

This post is a result of recent events with one of the companies that I work with. Sometimes, I help people because I want, sometimes because they pay me, mostly both ;). This time I've been helping one company decide on how to outsource their software development. They have many applications, some of them are old, some of them are younger, they constantly build something new as well - a never-ending story. I didn't want to get into the sole "picking the right company" part of this deal. I was not responsible for financial or any other non-programming part of this process, so instead of recommending companies I focused on something else: How to ensure the same (or better) quality, without having a dedicated team working close to all other people related to a given project.

I've spent some time studying their software, what they do, how they work and what their goals are. Also I've talked with their developers about their feelings and thoughts about all of this. I've spoken to other employees as well, and one thing struck me:

(Obrazek JPEG, 480×480 pikseli)

No one really cares! As long as it works, why would they? Programmers didn't have enough time (and sometimes knowledge), project managers didn't care as long as it worked (or also didn't know how to measure things like that), CEO thought that since there are so many apps, it is impossible to do this without a big overhead (and that this would cost a lot of money).

Low quality is just a way to postpone costs that later will be much higher

I can understand why CEOs can think like that. What I don't understand is why project managers and CTOs don't explain this to them. If CEO doesn't care, no one will be able to. And this will turn against everyone one day. Many poorly written projects are hard to give away. The more complicated they are, the more price grows.

Quality always costs. There's no doubt about that. But if you ensure it from the beginning, the further you go with your project the more you will gain. And I'm not talking only about money. Keep in mind, that people don't like other peoples code. And working with poorly written code is what they hate. Low quality equals a much higher rotation rate in teams that have to work with such code. Also keep in mind that everything changes. Programmers change their jobs, some companies are being closed, some are being created, and if you want to outsource stuff, you need to always be aware of that. The only thing that should not change from your perspective is your code quality.

It's always expensive to transfer knowledge and know-how

Outsourcing is not easy. Your team needs to transfer all the know-how to some other places and people. The more code there is, the harder it gets. But what could you do to make it go faster, easier and cheaper?

Ensure code quality!

You could ensure some code and documentation standards across all the firms that will work on your software. That way you can diversify across few that will be able to work with others code. If all of them share same principals, their work quality should be similar, their code should be readable for all of them and you could rotate across those companies according to your business needs. Further more you could even specify in the contract what you expect and what they need to obtain in terms of quality. Programmers will still make mistakes, things will still not work the way you wanted but even then standards will allow other people to fix those issues without any unexpected impact on the whole project. If you set the standards, programmers will have a bit less freedom in how they work and what they do. It's not always good but it is one of those nonfinancial costs you need to take.

Few tools you can use in order to move forward

Some "code related" tools that can help you out with Ruby based software:

  • Rspec (or any other test framework),
  • Simplecov,
  • YARD,
  • Rubocop.

Rspec (or any other test framework)

This is quite obvious. Tests are must be for any application that we want to maintain. Working with not tested software can be a nightmare. But how to measure tests/specs quality?

Simplecov to the rescue

We could (and we should!) use Simplecov. SimpleCov is a code coverage analysis tool for Ruby.

687474703a2f2f636f6c737a6f776b612e6769746875622e636f6d2f73696d706c65636f762f6465766973655f726573756c742d302e352e332e706e67

Picture taken from official Simplecov Github page

It will show you any flaws of your test suites. Not tested classes, methods, cases. It will also generate some useful statistics. If you require usage of this library from your contractors, you can include coverage level as one of parts of your contract. That way they will be obligated to keep tests up and running all the time. Of course they will have to agree on that, because if you force them to use it, they may just write tests that will "pass" Simplecov statistics, delivering you green, low quality tests/specs.

YARD - Yay! A Ruby Documentation Tool

I like self-explaining code. Ruby code can be written both in good and bad way. Unfortunately self-explaining code won't answer all the questions. For example, it won't answer why something is done that way, where there might be a (theoretically) better solution. Also an outsourced code often changes maintainers. None of them will pass all the knowledge to a next one. In cases like that I recommend full YARD documentation. At least on a module/class and public methods level.YARD is a documentation generation tool for the Ruby programming language. It enables the user to generate consistent, usable documentation that can be exported to a number of formats very easily

Some programmers write comments, some don't. But even if they do, without standardization, it's hard to read and maintain. If you use YARD, none of this will happen. You will end-up with a consistent, standardized documentation that can be viewed both online and offline. You can also easily monitor YARD doc coverage level by running:

yard stats --list-undoc

For example, you may get such result:

Files:          21
Modules:         5 (    0 undocumented)
Classes:        25 (    0 undocumented)
Constants:       8 (    1 undocumented)
Methods:        51 (    0 undocumented)
 98.88% documented

Undocumented Objects:

(in file: app/models/credit_card.rb)

Then it is quite clear that in file credit_card.rb some elements are undocumented and that developers should update docs. As you can see, YARD allows us to easily measure and monitor comments quality.

RuboCop - A Ruby static code analyzer, based on the community Ruby style guide

RuboCop is a Ruby static code analyzer. Out of the box it will enforce many of the guidelines outlined in the community Ruby Style Guide. So, instead of having code written in many ways, you can define a file called .rubocop that will contain all the rules about Ruby code style. That way, you can ensure same standards across many applications/dev teams/companies. It will notify you if anything is not as it should be.

.....C.................................................C......................C......

Offenses:

app/controllers/portal/base_controller.rb:40:3: 
C: Cyclomatic complexity for respond_with is too high. [8/6]
  def respond_with(*resources, &block)
  ^^^
app/controllers/portal/base_controller.rb:40:3: 
C: Method has too many lines. [18/15]
  def respond_with(*resources, &block)
  ^^^
app/controllers/application_controller.rb:52:3: 
C: Cyclomatic complexity for respond_with is too high. [8/6]
  def respond_with(*resources, &block)
  ^^^

Summary

Code quality is really important. It's also a topic for more than a blog post, but I hope you will consider this article useful. Tools that I've presented won't replace good developers but they can help you out omit troubles. If you use them wisely, you can ensure similar code quality in many dev teams.

Copyright © 2024 Closer to Code

Theme by Anders NorenUp ↑