views:

21

answers:

2

I'm trying to test a method on my model. Running in the console works, but my rspec test does not pass. Checkout the code:

Model:

def import(master)
  hsh = master.attributes.delete_if { |k,v| k == 'id' }
  self.update_attributes(hsh)
end

Rspec test:

describe "#import" do

  let(:master) { Factory(:sheet, :work_order => 'M1234', :sample_size => 10, :sample_scheme => 'TEST#') }
  let(:wo) { Factory(:sheet, :work_order => 'W1234', :sample_scheme => 'ORIG#' ) }

  it "imports all of the attributes from the master" do
    expect { wo.import(master) }.to change( wo, :sample_scheme ).to(master.sample_scheme)
  end

end

I can't figure this out, here is the output:

'Sheet#import imports all of the attributes from the master' FAILED
sample_scheme should have been changed to "TEST#", but is now "ORIG#"

As I said, the code correctly imports the attributes from the master when run in the console. It's just the rspec test is failing. What am I doing wrong?


change to import function results in passing:

def import(master)
  hsh = master.attributes.delete_if { |k,v| k == 'id' }
  hsh.each do |k,v|
    self.update_attribute(k, v)
  end
  #self.update_attribute(:sample_scheme, hsh['sample_scheme'])
  #self.update_attributes(hsh)
end
A: 

The change method is use if the number change, not if data change. You need test like that

describe "#import" do

  let(:master) { Factory(:sheet, :work_order => 'M1234', :sample_size => 10, :sample_scheme => 'TEST#') }
  let(:wo) { Factory(:sheet, :work_order => 'W1234', :sample_scheme => 'ORIG#' ) }

  it "imports all of the attributes from the master" do
    wo.sample_scheme.should.not == master.sample_scheme
    wo.import(master)
    wo.sample_scheme.should == master.sample_scheme
  end

end
shingara
I just tried it, and it still fails. This is making me feel dumb. This makes me think that it is not updating at all, even though the updat_attributes is returning true.
coreypurcell
have you try with a reload in last sentence just in case ?
shingara
Yes, I did. But this gets stranger. Check out the edit to the post, where I switch to using update_attribute. I wonder why this passes. I do have a before_update callback, but update_attributes is returning true, so it should be saving.
coreypurcell
A: 

Problem was my callback. For some reason I was reloading the model in the update callback. Not sure why I had that. That explains why save was returning true and my model still looked the like the old one. Thanks to shingara for his help. He got me thinking along the lines I needed.

coreypurcell