[rspec-users] Problem testing method

Matt Wynne matt at mattwynne.net
Thu Sep 25 05:27:31 EDT 2008


On 24 Sep 2008, at 16:02, Carlos Rafael Belizón Ibáñez wrote:
>
> Sorry, before I wrote with errors the example (it's the problem if you
> are remember without code at your face). This is the correct example
> with the suggestions to fix the problem:
>
> #foo.rb
> class Foo < ActiveRecord::Base
>   has_one :bar
>
>   def foo
>     self.bar.count -= 1
>   end
> end
>
> #foo_spec.rb
> require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
>
> describe Foo do
>   before(:each) do
>     @bar = stub_model(Bar, :count => 1)
>     @foo = Foo.new(:bar => @bar)
>     @before_value = @foo.bar
>   end
>
>   it "should decrement bar.count in 1" do
>     @foo.foo
>     @foo.bar.count.should be_equal(@value_before - 1)
>   end
> end
>
> #bar.rb
> class Bar < ActiveRecord::Base
> end
>
> And now, I got this error:
> 1)
> NoMethodError in 'Foo should decrement bar.count in 1'
> undefined method `count=' for #<Bar id: 1001, created_at: nil,
> updated_at: nil>
> /home/carlos/NetBeansProjects/RailsApplication1/app/models/foo.rb:5:in
> `foo'
> /home/carlos/NetBeansProjects/RailsApplication1/spec/models/ 
> foo_spec.rb:11:
>
> What it's wrong? Can I make this type of test with mock or stub?

You're expecting the Bar class to implement an interface which  
supports you calling count -= 1 on it.

Have you checked (for example, using script/console) that Bar does  
indeed offer this method? The error indicates that it doesn't, and  
from the code you've shown us I'd be surprised if it did - it's not  
something you can do to normal ActiveRecord objects - you'd have to  
destroy a particular instance, for example, for the result of count  
to go down.

I think it might be easier for us if you can show us an example  
that's closer to what you're actually trying to do.

cheers,
Matt
----
http://blog.mattwynne.net
http://songkick.com

In case you wondered: The opinions expressed in this email are my own  
and do not necessarily reflect the views of any former, current or  
future employers of mine.





More information about the rspec-users mailing list