在rspec中测试模块

时间:2009-10-09 10:09:43

标签: ruby unit-testing rspec

在rspec中测试模块的最佳实践是什么?我有一些模块包含在少数模型中,现在我只是对每个模型进行了重复测试(差异很小)。有没有办法让它干涸?

12 个答案:

答案 0 :(得分:199)

rad way =>

let(:dummy_class) { Class.new { include ModuleToBeTested } }

或者,您可以使用模块扩展测试类:

let(:dummy_class) { Class.new { extend ModuleToBeTested } }

使用'let'比使用实例变量来定义before(:each)中的虚拟类更好

When to use RSpec let()?

答案 1 :(得分:108)

麦克说。这是一个简单的例子:

模块代码......

module Say
  def hello
    "hello"
  end
end

spec fragment ...

class DummyClass
end

before(:each) do
  @dummy_class = DummyClass.new
  @dummy_class.extend(Say)
end

it "get hello string" do
  expect(@dummy_class.hello).to eq "hello"
end

答案 2 :(得分:23)

我在rspec主页上找到了更好的解决方案。显然它支持共享示例组。来自https://www.relishapp.com/rspec/rspec-core/v/2-13/docs/example-groups/shared-examples

  

共享示例组

     

您可以创建共享示例组   并将这些群体纳入其他群体   基团。

     

假设您有某些行为   适用于您的所有版本   产品,无论大小。

     

首先,将“共享”分解出来   行为:

shared_examples_for "all editions" do   
  it "should behave like all editions" do   
  end 
end
  

然后当你需要定义行为时   对于大型和小型版本,   使用引用共享行为   it_should_behave_like()方法。

describe "SmallEdition" do  
  it_should_behave_like "all editions"
  it "should also behave like a small edition" do   
  end 
end

答案 3 :(得分:21)

在我的脑海中,您是否可以在测试脚本中创建一个虚拟类并将模块包含在其中?然后测试虚拟类是否具有您期望的行为。

编辑:如果正如评论中所指出的那样,模块希望某些行为存在于混合的类中,那么我会尝试实现这些行为的虚拟变量。足以让模块乐于履行其职责。

那就是说,当一个模块从宿主那里得到很多东西(我们说“主机”?)类时,我对我的设计有点紧张 - 如果我还没有从基类继承或者可以不要将新功能注入继承树,然后我想我会尽量减少模块可能具有的任何期望。我担心的是我的设计会开始出现一些令人不愉快的不适应性。

答案 4 :(得分:10)

我认为接受的答案是正确的答案,但我想添加一个如何使用rpsecs shared_examples_forit_behaves_like方法的示例。我在代码段中提到了一些技巧,但有关详细信息,请参阅此relishapp-rspec-guide

有了这个,您可以在包含它的任何类中测试您的模块。 因此,您确实在测试您在应用程序中使用的内容。

让我们看一个例子:

# Lets assume a Movable module
module Movable
  def self.movable_class?
    true
  end

  def has_feets?
    true
  end
end

# Include Movable into Person and Animal
class Person < ActiveRecord::Base
  include Movable
end

class Animal < ActiveRecord::Base
  include Movable
end

现在让我们为我们的模块创建规范:movable_spec.rb

shared_examples_for Movable do
  context 'with an instance' do
    before(:each) do
      # described_class points on the class, if you need an instance of it: 
      @obj = described_class.new

      # or you can use a parameter see below Animal test
      @obj = obj if obj.present?
    end

    it 'should have feets' do
      @obj.has_feets?.should be_true
    end
  end

  context 'class methods' do
    it 'should be a movable class' do
      described_class.movable_class?.should be_true
    end
  end
end

# Now list every model in your app to test them properly

describe Person do
  it_behaves_like Movable
end

describe Animal do
  it_behaves_like Movable do
    let(:obj) { Animal.new({ :name => 'capybara' }) }
  end
end

答案 5 :(得分:6)

怎么样:

describe MyModule do
  subject { Object.new.extend(MyModule) }
  it "does stuff" do
    expect(subject.does_stuff?).to be_true
  end
end

答案 6 :(得分:6)

我建议对于较大且使用较多的模块,应该按照@Andrius here的建议选择“共享示例组”。对于你不想经历多个文件等问题的简单的东西,这里是如何确保最大程度地控制你的虚拟东西的可见性(用rspec 2.14.6测试,只需将代码复制并粘贴到一个spec文件并运行它):

module YourCoolModule
  def your_cool_module_method
  end
end

describe YourCoolModule do
  context "cntxt1" do
    let(:dummy_class) do
      Class.new do
        include YourCoolModule

        #Say, how your module works might depend on the return value of to_s for
        #the extending instances and you want to test this. You could of course
        #just mock/stub, but since you so conveniently have the class def here
        #you might be tempted to use it?
        def to_s
          "dummy"
        end

        #In case your module would happen to depend on the class having a name
        #you can simulate that behaviour easily.
        def self.name
          "DummyClass"
        end
      end
    end

    context "instances" do
      subject { dummy_class.new }

      it { subject.should be_an_instance_of(dummy_class) }
      it { should respond_to(:your_cool_module_method)}
      it { should be_a(YourCoolModule) }
      its (:to_s) { should eq("dummy") }
    end

    context "classes" do
      subject { dummy_class }
      it { should be_an_instance_of(Class) }
      it { defined?(DummyClass).should be_nil }
      its (:name) { should eq("DummyClass") }
    end
  end

  context "cntxt2" do
    it "should not be possible to access let methods from anohter context" do
      defined?(dummy_class).should be_nil
    end
  end

  it "should not be possible to access let methods from a child context" do
    defined?(dummy_class).should be_nil
  end
end

#You could also try to benefit from implicit subject using the descbie
#method in conjunction with local variables. You may want to scope your local
#variables. You can't use context here, because that can only be done inside
#a describe block, however you can use Porc.new and call it immediately or a
#describe blocks inside a describe block.

#Proc.new do
describe "YourCoolModule" do #But you mustn't refer to the module by the
  #constant itself, because if you do, it seems you can't reset what your
  #describing in inner scopes, so don't forget the quotes.
  dummy_class = Class.new { include YourCoolModule }
  #Now we can benefit from the implicit subject (being an instance of the
  #class whenever we are describing a class) and just..
  describe dummy_class do
    it { should respond_to(:your_cool_module_method) }
    it { should_not be_an_instance_of(Class) }
    it { should be_an_instance_of(dummy_class) }
    it { should be_a(YourCoolModule) }
  end
  describe Object do
    it { should_not respond_to(:your_cool_module_method) }
    it { should_not be_an_instance_of(Class) }
    it { should_not be_an_instance_of(dummy_class) }
    it { should be_an_instance_of(Object) }
    it { should_not be_a(YourCoolModule) }
  end
#end.call
end

#In this simple case there's necessarily no need for a variable at all..
describe Class.new { include YourCoolModule } do
  it { should respond_to(:your_cool_module_method) }
  it { should_not be_a(Class) }
  it { should be_a(YourCoolModule) }
end

describe "dummy_class not defined" do
  it { defined?(dummy_class).should be_nil }
end

答案 7 :(得分:6)

我最近的工作,使用尽可能少的硬接线

require 'spec_helper'

describe Module::UnderTest do
  subject {Object.new.extend(described_class)}

  context '.module_method' do
    it {is_expected.to respond_to(:module_method)}
    # etc etc
  end
end

我希望

subject {Class.new{include described_class}.new}

工作,但它没有(如在Ruby MRI 2.2.3和RSpec :: Core 3.3.0)

Failure/Error: subject {Class.new{include described_class}.new}
  NameError:
    undefined local variable or method `described_class' for #<Class:0x000000063a6708>

显然,describe_class在该范围内不可见。

答案 8 :(得分:4)

您也可以使用辅助类型

# api_helper.rb
module Api
  def my_meth
    10
  end
end
# spec/api_spec.rb
require "api_helper"

RSpec.describe Api, :type => :helper do
  describe "#my_meth" do
    it { expect( helper.my_meth ).to eq 10 }
  end
end

以下是文档:https://www.relishapp.com/rspec/rspec-rails/v/3-3/docs/helper-specs/helper-spec

答案 9 :(得分:1)

要测试您的模块,请使用:

describe MyCoolModule do
  subject(:my_instance) { Class.new.extend(described_class) }

  # examples
end

要使您在多个规范中使用的某些东西干燥,可以使用共享上下文:

RSpec.shared_context 'some shared context' do
  let(:reused_thing)       { create :the_thing }
  let(:reused_other_thing) { create :the_thing }

  shared_examples_for 'the stuff' do
    it { ... }
    it { ... }
  end
end
require 'some_shared_context'

describe MyCoolClass do
  include_context 'some shared context'

  it_behaves_like 'the stuff'

  it_behaves_like 'the stuff' do
    let(:reused_thing) { create :overrides_the_thing_in_shared_context }
  end
end

资源:

答案 10 :(得分:0)

您只需将模块包含在spec文件中即可 mudule Test module MyModule def test 'test' end end end 在您的spec文件中 RSpec.describe Test::MyModule do include Test::MyModule #you can call directly the method *test* it 'returns test' do expect(test).to eql('test') end end

答案 11 :(得分:-1)

这是一种循环模式,因为您将需要测试多个模块。出于这个原因,为此创建一个助手是非常可取的。

我发现this post会说明如何执行此操作,但由于这里的网站可能会在某个时候被关闭,因此我在这里应对。

这是为了避免 对象实例未实现实例方法:尝试在{{1}上使用allow方法时遇到的:whatever 错误}类。

代码:

dummy

spec/support/helpers/dummy_class_helpers.rb

module DummyClassHelpers def dummy_class(name, &block) let(name.to_s.underscore) do klass = Class.new(&block) self.class.const_set name.to_s.classify, klass end end end

spec/spec_helper.rb

在您的规格中:

# skip this if you want to manually require
Dir[File.expand_path("../support/**/*.rb", __FILE__)].each {|f| require f}

RSpec.configure do |config|
  config.extend DummyClassHelpers
end