【发布时间】:2009-10-02 08:32:10
【问题描述】:
以下规范有效,但我知道它不应该是这样的。我很难理解 rspec,尤其是模拟和存根。
这是型号代码
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
这是我写的规范
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
首先,我的规格比我的方法要大得多,而且我使用的是真正的产品。关于为此编写更好的规范的一些指示将非常有帮助。另外,如果有人知道使用模拟和存根学习 rspec 的好资源,请您添加一些链接。
谢谢
【问题讨论】:
标签: ruby-on-rails rspec