My Rails 3应用程序有一个产品资源。
在我的ProductsController规范中,生成的测试确保我在更新后重定向到产品的URL。
以下代码错误:
#inside ProductsController spec
def mock_product(stubs={})
(@mock_product ||= mock_model(Product).as_null_object).tap do |product|
product.stub(stubs) unless stubs.empty?
end
end
it "should do something" do
product_url(mock_product)
end
错误是:
TypeError: RSpec::Mocks::Mock#to_hash should return Hash
答案 0 :(得分:0)
我的mock_model定义为__null_object(这意味着它将通过返回自身来响应所有消息,除了那些消息。
因此,rails路由助手(如product_url(product))首先将产品转换为散列,然后使用产品['id']生成路径。
由于我的mock_product没有存根to_hash,因此“as_null_object”行为优先
irb > mock_product
=> #<Product:0x..fdb3b6176 @name="Product_1028">
irb > mock_product.to_hash
=> #<Product:0x..fdb3b6176 @name="Product_1028">
我的解决方案是存根to_hash:
irb > mock_product(:to_hash => {:id => 1 }).to_hash
=> {:id=>1}
默认情况下,这应该包含在mock_product模型中吗?