The following spec works but I know it shouldn't be like this. I am having a hard time getting my head around rspec, in particular mocks and stubs.
This is the model code
class RecipeFermentable < ActiveRecord::Base
belongs_to :recipe
belongs_to :product
def set_attributes()
attrs = product.product_attributes
self.ppg = attrs.find_by_name(:ppg.to_s).value
self.ecb = attrs.find_by_name(:ecb.to_s).value
end
end
And this is the spec I have written
it "should set the attributes from the product" do
@product_attribute1 = mock_model(ProductAttribute, :name => :ppg, :value => 40)
@product_attribute2 = mock_model(ProductAttribute, :name => :ecb, :value => 1)
@product = Product.new
@product.product_attributes << @product_attribute1
@product.product_attributes << @product_attribute2
@recipe_fermentable = RecipeFermentable.new
@recipe_fermentable.product.should_receive(:product_attributes).and_return(@product_attributes)
@product_attributes.stub(:find_by_name).with(:ppg.to_s).and_return(@product_attribute1)
@product_attributes.stub(:find_by_name).with(:ecb.to_s).and_return(@product_attribute2)
@recipe_fermentable.set_attributes
@recipe_fermentable.ppg.should eql(40)
@recipe_fermentable.ecb.should eql(1)
end
For a start my spec is way bigger than my method, and I am using a real Product. Some pointers on the way to write a goodbetter spec for this would be really helpfull. Also if anyone knows of a good resource for learning rspec using mocks and stubs, please could you add some links.
Thanks