Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use rspec expectations and matchers outside of Rspec?

I have a script which has evolved into needing to do some assertions and matching.

It is written in ruby, and I have included rspec in the Gemfile and required it.

I found this very helpful SO post on how to use in irb:

How to use RSpec expectations in irb

I also found the following:

Use RSpec's "expect" etc. outside a describe ... it block

class BF
   include ::Rspec::Matchers

   def self.test
     expect(1).to eq(1)
   end
end

BF.test

I get an error at the expect line.

like image 265
Satchel Avatar asked Sep 15 '15 19:09

Satchel


1 Answers

When you include a module, it makes its methods available to instances of the class. Your test method is a singleton method (a "class method"), not an instance method, and thus will never have access to methods provided by mixed-in modules. To fix it, you can do:

class BF
   include ::RSpec::Matchers

   def test
     expect(1).to eq(1)
   end
end

BF.new.test

If you want the RSpec::Matchers methods to be available to singleton methods of BF, you can instead extend the module:

class BF
   extend ::RSpec::Matchers

   def self.test
     expect(1).to eq(1)
   end
end

BF.test
like image 157
Myron Marston Avatar answered Nov 10 '22 01:11

Myron Marston