【发布时间】:2010-07-07 00:13:38
【问题描述】:
我试图在我的 RSpec 测试中指定我的控制器应该使用 current_user.projects.find() 而不是 Project.find() 我正在使用 Mocha 模拟框架并且正在尝试这样的事情:
controller.current_user.projects.expects(:find).returns(@project)
我已经嘲笑了controller.stubs(:current_user).returns(@profile)
即使我使用Project.find() 实现,这个测试也通过了。如何测试我的控制器是否调用了正确的对象?
编辑(添加额外代码):
我有项目和任务,项目有很多任务。这是 current_user 拥有的项目中显示任务的 show 方法
控制器中的动作:
def show
@project = current_user.projects.find_by_id(params[:cardset_id])
if @project.nil?
flash[:notice] = "That project doesn't exist. Try again."
redirect_to(projects_path)
else
@task = @project.tasks.find_by_id(params[:id])
end
end
这是不检查 cardsets 方法是否被 current_user 对象调用的测试。
当前测试:
context "with get to show" do
context "with valid project" do
before(:each) do
@project = Factory(:project)
@task = Factory(:task)
@profile = @project.profile
ApplicationController.stubs(:require_user).returns(true)
controller.stubs(:current_user).returns(@profile)
Project.stubs(:find_by_id).returns(@project)
@project.tasks.stubs(:find_by_id).returns(@task)
get :show, :project_id => @project.id, :id => @task.id
end
it "should assign task" do
assigns[:task].should_not be_nil
end
it "should assign project" do
assigns[:project].should_not be_nil
end
end
context "with invalid project" do
before(:each) do
Project.stubs(:find_by_id).returns(nil)
get :show, :project_id => @project.id, :id => @task.id
end
it "should set flash" do
flash[:notice].should match(/doesn't exist/i)
end
it "should redirect" do
response.should redirect_to(cardsets_url)
end
end
end
【问题讨论】:
-
提供更多来自测试和控制器的代码可能会有所帮助。如果显然没有达到预期,那么测试如何通过还不清楚。
标签: ruby-on-rails unit-testing rspec stub mocha.js