2011-10-24 43 views
1

所以,我一直在殴打我的头一阵子,只是不能取得任何进展。Mongoid和RSpec的ID问题

我有以下的控制器动作:

def create 
    @job = Job.new(params[:job]) 

    respond_to do |format| 
    if @job.save 
     flash[:notice] = "The Job is ready to be configured" 
     format.html { redirect_to setup_job_path(@job.id) } 
     format.json { head :ok } 
    else 
     format.html { redirect_to new_job_path, notice: 'There was an error creating the job.' } 
     format.json { render json: @job.errors, status: :unprocessable_entity } 
    end 
    end 
end 

我试图测试这个动作。这是我对成功创建重定向的测试。

let (:job) { mock_model(Job).as_null_object } 

我不断收到以下错误:

it "redirects to the Job setup" do 
    job.stub(:id=).with(BSON::ObjectId.new).and_return(job) 
    job.stub(:save) 
    post :create 
    response.should redirect_to(setup_job_path(job.id)) 
end 

工作是整个套件这里定义

2) JobsController POST create when the job saves successfully redirects to the Job setup 
Failure/Error: response.should redirect_to(setup_job_path(job.id)) 
    Expected response to be a redirect to <http://test.host/jobs/1005/setup> but was a redirect to <http://test.host/jobs/4ea58505d7beba436f000006/setup> 

我已经尝试了一些不同的东西,但不管我尝试我似乎无法在我的测试中得到正确的对象ID。

回答

1

如果你存根:id=你正在创建一个非常弱的测试。事实上,除非你对Mongoid内部信号超级自信,否则如果Mongoid改变它产生id的方式,你的测试将会中断。事实上,它不起作用。

另外,请记住您创建了一个job变量,但您没有在控制器内部传递此变量。这意味着,在:create行动将在

@job = Job.new(params[:job]) 

初始化自己的工作实例,它会完全忽略你job。我建议你使用assigns

it "redirects to the Job setup" do 
    post :create 
    response.should redirect_to(setup_job_path(assigns(:job))) 
end 
+0

谢谢!我是rspec新手,似乎忘记了分配。 – LeakyBucket