[rspec-users] Stubbing Model.new w/ block?
dchelimsky at gmail.com
Fri Apr 20 18:56:34 EDT 2007
On 4/20/07, David Chelimsky <dchelimsky at gmail.com> wrote:
> On 4/20/07, James Hillyerd <james at hillyerd.com> wrote:
> > Ok, I followed the advice of the list and moved more code into my
> > model from my controller. When developing tests for this new code, I
> > ran into a problem...
> > My model code creates a receipt object and sets some values on it:
> > @receipt = Receipt.new do |r|
> > r.x = 1
> > r.y = 2
> > # etc
> > end
> > I wanted to be able to stub out Receipt.new so that I could set
> > expectations on the methods called on the resulting Receipt object.
> > If in my test setup I do:
> > @receipt = mock_receipt
> > Receipt.stub!(:new).and_return(@receipt)
> > The block part of the code will never be called. If I do:
> > Receipt.stub!(:new).and_yield(@receipt)
> > Then @receipt in my model will be set to the return value of the block.
> > I also tried something along the lines of:
> > Receipt.stub!(:new) do
> > yield @receipt
> > @receipt
> > end
> > but got some weird no block error.
> > Help? Am I going about this all wrong?
> Any reason you don't just query a real receipt object?
> describe Person do
> it "should create an initialized person" do
> Person.create_initialized("Michael").name.should == "Michael"
> class Person
> class << self
> def create_initialized(name)
> Person.new do |p|
> p.name = name
> What you're trying to mock here doesn't seem to buy you much. Unless
> I'm missing something.
I just tried this:
irb(main):001:0> class Receipt
irb(main):002:1> attr_accessor :name
irb(main):004:0> r = Receipt.new do |r|
irb(main):005:1* r.name = "Ruby"
Does AR do something special w/ Model.new that Ruby doesn't do already?
> > -james
> > --
> > James A. Hillyerd <james at hillyerd.com>
> > Chief Technical Officer - ActiveRain Corp
> > _______________________________________________
> > rspec-users mailing list
> > rspec-users at rubyforge.org
> > http://rubyforge.org/mailman/listinfo/rspec-users
More information about the rspec-users