Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert that a class will respond_to a class method with RSpec?

Tags:

ruby

rspec2

Let's say I have a class definition like so:

class Foo
  def init(val)
    @val = val
  end

  def self.bar
    :bar
  end

  def val
    @val
  end
end

with a spec like:

describe Foo
  it { should respond_to(:val) }
  it { should respond_to(:bar) }
end

The second it assertion fails. It isn't clear to me from RSpec's documentation that respond_to should fail on class methods.

like image 790
troutwine Avatar asked Apr 19 '12 15:04

troutwine


2 Answers

Nowadays it is suggested we use expect, like this:

describe Foo do
  it 'should respond to :bar' do
    expect(Foo).to respond_to(:bar)
  end
end

See: http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/


OLD ANSWER:

Actually you can make this approach by providing a subject:

describe Foo do
  subject { Foo }
  it { should respond_to :bar } # :bar being a class method
end

As described in here: http://betterspecs.org/#subject

like image 61
Arthur Corenzan Avatar answered Nov 04 '22 03:11

Arthur Corenzan


Your example should be written like this:

it 'should respond to ::bar' do
  Foo.should respond_to(:bar)
end
like image 20
Brandan Avatar answered Nov 04 '22 04:11

Brandan