How to check whether a variable is an instance of a module's subclass using rspec?

不羁岁月 提交于 2019-12-25 04:22:39

问题


I have a class structure that looks like this:

module MyModule

    class MyOuterClass

        class MyInnerClass

        end

    end

end

I'm trying to make sure that a variable was correctly instantiated as a MyInnerClass using Rspec. printing the type of the class, it was MyModule::MyOuterClass::MyInnerClass. However, if I try to run the line

expect{@instance_of_MyInnerClass}.to be_an_instance_of(MyModule::MyOuterClass::MyInnerClass)

I get the error "You must pass an argument rather than a block to use the provided matcher." Additionally, the classes are in another location, so I can't just check

[...] be_an_instance_of(MyInnerClass)

Rspec complains that MyInnerClass is an uninitialized constant. So, I would like to ask how to verify that a variable is an instance of MyInnerClass using RSpec.


回答1:


Don't Pass a Block

Rspec 3.x uses an expect method rather than a block syntax (see RSpec 3 Expectations 3.0). To get your spec to pass, and clean it up, you can use the following:

module MyModule
  class MyOuterClass
    class MyInnerClass
    end
  end
end

describe MyModule::MyOuterClass::MyInnerClass do
  it "is correctly instantiated" do
    expect(subject).to be_an_instance_of MyModule::MyOuterClass::MyInnerClass
  end
end

Note the use of the implicit subject, passed as an argument to #expect. You can certainly pass other local or instance variables instead, but in this case subject is already defined for you as MyModule::MyOuterClass::MyInnerClass.new.




回答2:


Most of us are using the preferred Rspec syntax, so it would be:

expect(@instance_of_MyInnerClass).to be_a MyInnerClass


来源:https://stackoverflow.com/questions/24144460/how-to-check-whether-a-variable-is-an-instance-of-a-modules-subclass-using-rspe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!