【发布时间】:2011-05-13 09:05:00
【问题描述】:
在一个 rails 3 应用程序中,我正在使用 mocha 在我的功能测试中进行一些模拟。但是,它似乎没有模拟功能控制器中的类方法。
控制器代码
class TagsController < ApplicationController
respond_to :json
def index
response = User.tags_starting_with(params[:query])
respond_with response
end
end
功能测试
class TagsControllerTest < ActionController::TestCase
context "index action with query" do
setup do
query = "A_QUERY"
get :index, :query => query, :format => "json"
@tags = ["these", "are", "test", "tags"]
User.expects(:tags_starting_with).returns(@tags).once
end
should "return JSON formatted tags array" do
tags = JSON::parse @response.body
assert_equal @tags, tags
end
end
end
宝石文件
gem "mocha"
如果我运行这个测试,我会一直遇到
- expected exactly once, not yet invoked: User.tags_starting_with(any_parameters)
如果我使用rails console test,我可以很好地模拟一个类方法,并且它可以按预期工作。
我已经完成了this post 并完成了 Gemfile,require "false" 位。但无济于事,它只是不想在控制器中模拟User的类方法。
我尝试过的其他事情,如果我在测试本身中执行User.tags_starting_with("bla"),则期望通过。
那么关于为什么控制器中的User 没有被正确模拟的任何想法?
【问题讨论】: