How to test class methods in RSPEC

lulalala picture lulalala · Nov 4, 2011 · Viewed 35.6k times · Source

I wrote a simple class method Buy.get_days(string), and is trying to test it with different text string inputs. However I feel it is very verbose.

  • Is there any more concise way to test the following?
  • Is there a equivalent of subject for methods which I can just keep passing different parameters in and check the results?
  • Is there a way to avoid the unnecessary description at each it?

thanks

 describe Buy do
   describe '.get_days' do
    it 'should get days' do
      Buy.get_days('Includes a 1-weeknight stay for up to 4 people')
      .should == 1
      end
    it 'should get days' do
      Buy.get_days('Includes a 1-night stay in a King Studio Room with stone fireplace')
      .should == 1
    end
    it 'should get days' do
      Buy.get_days('Includes 4 nights/5 days at the Finisterra Hotel for up to two adults and two children (staying in the same room)')
      .should == 4
    end
  end
end

Answer

ahnbizcad picture ahnbizcad · Mar 18, 2015

Apparently there is a described_class method.

https://www.relishapp.com/rspec/rspec-core/docs/metadata/described-class

I suppose it's cleaner than subject.class, since it doesn't introduce another . method call, which reduces readability.

Using either described_class or subject.class may be more DRY than mentioning the class explicitly in every example. But personally I think not getting the syntax highlighting that comes with mentioning the class name explicitly is kind of a bummer, and I think it reduces readability, despite it totally winning in the maintainability department.

A question arises regarding best practice:

Should you use described_class whenever possible inside and outside the .expect() method, or only within the expect() method?