Testing modules in rspec

What are the best practices on testing modules in rspec? I have some modules that get included in few models and for now I simply have duplicate tests for each model (with few differences). Is there a way to DRY it up?


The rad way =>

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

Alternatively you can extend the test class with your module:

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

Using 'let' is better than using an instance variable to define the dummy class in the before(:each)

When to use RSpec let()?


What mike said. Here's a trivial example:

module code...

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

For modules that can be tested in isolation or by mocking the class, I like something along the lines of:

module:

module MyModule
  def hallo
    "hallo"
  end
end

spec:

describe MyModule do
  include MyModule

  it { hallo.should == "hallo" }
end

It might seem wrong to hijack nested example groups, but I like the terseness. Any thoughts?

链接地址: http://www.djcxy.com/p/59294.html

上一篇: Rspec:“array.should == another

下一篇: 在rspec中测试模块