我正在使用 Mocha,并试图在功能测试中使用它。
这是我的代码:
test "should post create" do
user = FactoryGirl.create(:user)
UserSession.create(user)
recipe_attributes = FactoryGirl.attributes_for(:recipe)
Recipes::Recipe.any_instance.expects(:save)
post(:create, {'recipes_recipe' => recipe_attributes})
assert_response(302)
assert_not_nil(assigns(:recipe))
end
代码未能assert_response(302)
说明响应为200
. 当我删除该行时:
Recipes::Recipe.any_instance.expects(:save)
测试通过。
这是create
动作:
def create
@recipe = Recipe.new(params[:recipes_recipe])
photo_keys = params.keys.select{|k|k.match(/^photo/)}
@photos = []
photo_keys.each do |photo_key|
@photos << Photo.new(params[photo_key])
end
@recipe.tags = Tag.parse(params[:tags])
@recipe.author = current_user
photos_valid = !@photos.empty? ? @photos.all?{|photo|photo.save} : true
puts photos_valid.inspect
if @recipe.save && photos_valid
unless @photos.empty?
@photos.each do |photo|
photo.recipe_id = @recipe.id
photo.save
end
end
flash[:notice] = 'Recipe was successfully created.'
redirect_to recipe_url(@recipe.slug)
else
puts @recipe.save.inspect
puts @recipe.errors.inspect
flash[:error] = 'Could not create recipe. '
flash[:error] += 'Please correct any mistakes below.'
render 'new'
end
end
当我puts Recipes::Recipe.all.inspect
在else
子句中放入 a 时,列表是空的,我想这应该是它应该如何工作的,因为 Mocha 的重点是不接触数据库以使测试更快。
所以,我的问题是,在这种情况下我应该如何进行测试?这条线是否足以确保该create
操作按应有的方式进行?
Recipes::Recipe.any_instance.expects(:save)