My Rails 3 application has a Product resource.
In my ProductsController specs, the generated tests are making sure that I redirect to a product's url afer updating it.
The following code errors:
开发者_StackOverflow中文版#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
The error is:
TypeError: RSpec::Mocks::Mock#to_hash should return Hash
My mock_model is defined as_null_object (which means that it will respond to all messages, except those stubbed, by returning itself.
So, rails routing helpers (like product_url(product)) first converst the product to a hash, and uses the product['id'] to generate the route.
Since my mock_product didn't stub to_hash, the "as_null_object" behavior took precedence
irb > mock_product
=> #<Product:0x..fdb3b6176 @name="Product_1028">
irb > mock_product.to_hash
=> #<Product:0x..fdb3b6176 @name="Product_1028">
My solution was to stub to_hash:
irb > mock_product(:to_hash => {:id => 1 }).to_hash
=> {:id=>1}
Should this be included in the mock_product model by default?
精彩评论