[rspec-users] Stubbing times: #from_now et al.

David Chelimsky dchelimsky at gmail.com
Wed Nov 5 14:42:47 EST 2008


On Wed, Nov 5, 2008 at 12:51 PM, Nick Hoffman <nick at deadorange.com> wrote:
> I had a look around for how to stub Time.now , #from_now , etc, and came
> across this, which was useful:
> http://devblog.michaelgalero.com/2007/11/23/actioncontroller-rspec-stub-timenow/
>
> Unfortunately, my situation is slightly different, and causes that solution
> to not be applicable. This is what I'm trying to spec:
>
> def remember_me_for(time)
>  remember_me_until time.from_now.utc
> end
>
> I thought this would work:
>
> it 'should remember a user for a period of time' do
>  user          = create_user
>  one_week      = 1.week
>  from_now      = 1.week.from_now
>  from_now_utc  = 1.week.from_now.utc
>
>  one_week.stub!(:from_now).and_return from_now
>  from_now.stub!(:utc).and_return from_now_utc
>
>  user.should_receive(:remember_me_until).with from_now_utc
>
>  user.remember_me_for one_week
> end
>
> But that fails, referencing the stub on "one_week":
>
> TypeError in 'User should remember a user for a period of time'
> no virtual class for Fixnum
>
> Any suggestions for how to solve this? Thanks!

Looks like you can't stub anything on a Fixnum because of the way
RSpec's mocking works.

>> require 'spec/mocks'
=> true
>> 1.stub!(:foo)
TypeError: no virtual class for Fixnum

Same with mocha, apparently.

>> require 'mocha'
=> true
>> 1.stubs(:foo)
TypeError: no virtual class for Fixnum

Same with rr:

>> require 'rr'
=> true
>> mock(1).foo
TypeError: no virtual class for Fixnum

And lastly (but not leastly), flexmock:

>> require 'flexmock'
>> include FlexMock::MockContainer
=> Object
>> flexmock(1).foo
TypeError: no virtual class for Fixnum


The problem is there is no Singleton Class for 1, probably an
efficiency in Ruby since 1 is, itself, a Singleton.

All of these frameworks try to manipulate methods on the object's
singleton class. So no mocking/stubbing on Fixnums. Apparently.

Not much help - sorry.

David

> Nick


More information about the rspec-users mailing list