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

1

8

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.

Marinemarinelli answered 15/9, 2015 at 19:15 Comment(1)
... What error do you get?Autocracy
B
10

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
Bay answered 15/9, 2015 at 19:32 Comment(1)
ah, it is the extend that looks like what I want it to do! Tryuing now!Marinemarinelli

© 2022 - 2024 — McMap. All rights reserved.