Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

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') }
person = Person.new('Jim', 32)

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

reference: rspec have-attributes-matcher

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top