Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec one-liner to test object's attributes

Tags:

ruby

rspec

Let's assume following situation

class A
    attr_accessor :name
    def initialize(name)
        @name = name
    end
end

subject { A.new('John') }

then I'd like to have some one-liner like this

it { should have(:name) eq('John') }

Is it possible somehow?

like image 349
Misha Slyusarev Avatar asked Nov 08 '13 09:11

Misha Slyusarev


2 Answers

Method its was removed from RSpec https://gist.github.com/myronmarston/4503509. Instead you should be able to do the one liner this way:

it { is_expected.to have_attributes(name: 'John') }
like image 187
Misha Slyusarev Avatar answered Sep 27 '22 16:09

Misha Slyusarev


Yes, it is possible, but the syntax you want to use (using spaces everywhere) has the implicatiion that have(:name) and eq('John') are all arguments applied to the method should. So you would have to predefine those, which cannot be your goal. That said, you can use rspec custom matchers to achieve a similar goal:

require 'rspec/expectations'

RSpec::Matchers.define :have do |meth, expected|
  match do |actual|
    actual.send(meth) == expected
  end
end

This gives you the following syntax:

it { should have(:name, 'John') }

Also, you can use its

its(:name){ should eq('John') }
like image 24
Beat Richartz Avatar answered Sep 27 '22 15:09

Beat Richartz