开发者

How to stub DataMapper association with RSpec2?

I'm trying to write some specs and want to stub out the calls to the database so I don't rely on an开发者_StackOverflow actual filled database to get the tests running.

Now I don't really know how to stub the calls between associations using DataMapper.

Here are two example models:

class Foo
  include DataMapper::Resource

  property :id, Serial

  has n, :bars
end

class Bar
  include DataMapper::Resource

  property :id, Serial

  belongs_to :foo
end

Now I want to stub the call to Foo.first('foobar') and Foo.first('foobar').bars The first one is no problem using Foo.stub(:first) { #etc } but I don't know how to stub the second call to its associations. Something like Foo.stub(:bars) { #etc } is not working.

Does anyone know how to do it? Is this approach even correct?

Thanks in advance.


I would use a mock_model.

foo = mock(Foo).as_null_object
foo.stub(:bars)
Foo.stub(:first).and_return(foo)

The reason for the as_null_object is that RSpec will return false by default when asked if it respends to a method that it hasn't been told to expect.

If that doesn't work, then create an instance of foo.

foo = Foo.create(:example => "data") #Or create with a factory a factory
foo.stub(:bars)
Foo.stub(:first).and_return(foo)

Then when you do:

Foo.first('foobar').bars

it will use the stub on line 2 as the first call will return that instance of foo.


not tested, but it should work:

Foo.stub(:first) { ... }
foo = Foo.first('foobar')
foo.stub(:bars) { ... }

regards,

A.


You can use stub_chain method:

Foo.stub_chain(:first, :bars).and_return(:whatever)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜