Misha Slyusarev
Misha Slyusarev

Reputation: 1383

RSpec one-liner to test object's attributes

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?

Upvotes: 9

Views: 11630

Answers (3)

Vbp
Vbp

Reputation: 1962

person = Person.new('Jim', 32)

expect(person).to have_attributes(name: 'Jim', age: 32)

reference: rspec have-attributes-matcher

Upvotes: 5

Misha Slyusarev
Misha Slyusarev

Reputation: 1383

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') }

Upvotes: 14

Beat Richartz
Beat Richartz

Reputation: 9622

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') }

Upvotes: 5

Related Questions