[rspec-users] more rspec questions

Adam Sroka adam.sroka at gmail.com
Tue Apr 27 19:31:28 EDT 2010


If something in the code you are testing depends on the return value
of a method then you would use a stub. e.g.:

foo = mock(Foo)
foo.stub!(:slave_method).and_return("foo")

However, in some cases what matters is not what the method returns but
the fact that slave_method gets called. i.e.:

foo.should_receive(:slave_method)

There is plenty of info about this in the RSpec docs.

Re-reading your example, I don't think I would mock Vcard. From what I
can see Vcard reads data that you got from a file and creates a list
of Contact objects from it. The only interesting thing about Vcard is
that it is able to parse this data in string form. So, I would write a
spec for that (i.e. what are the interesting permutations of strings
that Vcard can parse? And what representation should result from
parsing them?)

The second interesting thing is that I can create new Contacts and put
them into the collection that Vcard maintains. I would consider
separating the parsing from maintaining the list as these seem like
different responsibilities.

There really doesn't seem to be anything else going on here from the
information you've given. Contact and Email seem like pure values, so
there probably isn't any point in mocking them. However, if they
contain some interesting behavior then that should be tested as well.

On Tue, Apr 27, 2010 at 4:02 PM, Patrick J. Collins
<patrick at collinatorstudios.com> wrote:
>> Based on the above I think the Vcard is a good opportunity for a mock.
>> That would most likely imply that you create the Vcard somewhere else
>> and pass it into this method. Also, you should directly test the
>
> Ok, and regarding mocking--  Something that is still very unclear to me is how
> can I affect instance variables through mocking?  If I do:
>
>
> def master_method
>  @foo = "foo"
>
>  slave_method
> end
>
> def slave_method
>
>  @foo
>
> end
>
> ..
>
> it "should be foo" do
>
>  foo = mock_model(Foo)
>
>  foo.slave_method.should == "foo"
>
> end
>
> ...
>
>
> This will be false because @foo is set in the msater method which I am
> bypassing because I just want to test the slave method.  So how can I set an
> instance variabel within my spec so that @foo will be properly set?  Should I
> use setter/getter methods in this case??
>
> def master_method
>  foo = "foo"
>
>  slave_method
> end
>
> def slave_method
>
>  foo
>
> end
>
> def foo=(new_foo)
>  @foo = new_foo
> end
>
> def foo
>  @foo
> end
>
> ......... ?  Is that the way to go???
>
> Patrick J. Collins
> http://collinatorstudios.com
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>


More information about the rspec-users mailing list