solnic/virtus — Issue #78: Virtus coercion and RSpec doubles
Author: lminaudier
Created: 2012-02-28 13:49:48+00:00
State: open

Hi,

I run into a minor issue with Virtus when trying to write some specs of a Virtus Object.

Here is a spec that describe the problem.

```ruby
require 'spec_helper'

class Poro
include Virtus

attribute :id, Integer
attribute :name, String
end

describe Poro do
subject { Poro.new }

# This spec fails
it 'accepts RSpec String doubles' do
name = double
subject.name = name

subject.name.should == name
end

# Those pass
it 'accepts RSpec Integer doubles' do
id = double
subject.id = id

subject.id.should == id
end

it 'accepts integer attributes' do
subject.id = 1

subject.id.should == 1
end

it 'accepts string attributes' do
subject.name = 'foo bar'

subject.name.should == 'foo bar'
end
end
```

The first spec failed with this message

```
Failures:

1) Poro accepts RSpec String doubles
Failure/Error: subject.name.should == name
expected: #
got: "#[RSpec::Mocks::Mock:0x3fe5188fb58c @name=nil]" (using ==)
Diff:
@@ -1,2 +1,2 @@
-#
+"#[RSpec::Mocks::Mock:0x3fe5188fb58c @name=nil]"
# ./spec/integration/bug_spec.rb:25:in `block (2 levels) in '

Finished in 0.00176 seconds
1 example, 1 failure
```

It is pretty clear that the `double` is converted into a `String` but that is not what I expect.

To fix this issue, I add a custom coercion object.

```ruby
module Virtus
class Coercion
class Mock < Virtus::Coercion::Object
primitive ::RSpec::Mocks::Mock

def self.to_string(value)
value
end
end
end
end
```

But, I'm pretty sure that it is not the right way to fix the problem.

What do you think of this issue ?