Friday, August 1, 2014

RSpec Advanced Subject

So, as we all know, we shouldn't use subject. But what if you really like one liner syntax?

I am working on an attempt to make subject more dynamic and allow the use of one lines in more places. I am doing this by parsing describe arguments and adding a couple new blocks in order to build the subject dynamically.

For example:

describe Object do
  describe '#nil?' do
    it { should be_false }
  end
end

Will be parsed to know that the subject under test is the following: Object.new.nil?

What about class methods and methods with arguments?

describe File do
  describe '.read' do
    when_passed 'file.txt' do
      it { should eq('contents of file.txt') }
    end
  end
end

This will be parsed as
File.read('file.txt'). This works by storing the method, what the method is called on, and what is passed to the method and putting it all together within a proc that is called as the hidden subject. A period before the method indicates it is a class method and a hash indicates it is an instance method.

Finally there is a way to pass variables to the initializer:


describe Array do
  when_initialized_with 2 do
    it { should eq [nil, nil] }
  end
end

This is just the basics and I am looking for feedback and more feature ideas. Currently I am trying to figure out passing blocks and how #let fits in.

rspec-advanced_subject