Rspec,测试更新控制器不工作?

Pau*_*l L 5 rspec ruby-on-rails-3

这是我正在努力熟悉TDD和Rspec的作业.但不知何故,我不明白为什么以下测试失败:

 describe 'update' do
    fixtures :movies
    before :each do
      @fake_movie = movies(:star_wars_movie)
    end
    it 'should retrieve the right movie from Movie model to update' do
      Movie.should_receive(:find).with(@fake_movie.id.to_s).and_return(@fake_movie)
      put :update, :id => @fake_movie.id, :movie => {:rating => @fake_movie.rating}
    end

    it 'should prepare the movie object available for update' do
      put :update, :id => @fake_movie.id, :movie => {:rating => @fake_movie.rating}
      assigns(:movie).should == @fake_movie
    end

    it 'should pass movie object the new attribute value to updated' do
      fake_new_rating = 'PG-15'
       @fake_movie.stub(:update_attributes!).with("rating" => fake_new_rating).and_return(:true)
      put :update, :id => @fake_movie.id, :movie => {:rating => fake_new_rating}
      @fake_movie.should_receive(:update_attributes!).with("rating" => fake_new_rating).and_return(:true)
    end
  end
Run Code Online (Sandbox Code Playgroud)

我得到的错误信息是:

Failures:

  1) MoviesController update should pass movie object the new attribute value to updated
     Failure/Error: @fake_movie.should_receive(:update_attributes!).with("rating" => fake_new_rating).and_return(:true)
       (#<Movie:0xd39ea38>).update_attributes!({"rating"=>"PG-15"})
           expected: 1 time
           received: 0 times
     # ./spec/controllers/movies_controller_spec.rb:99:in `block (3 levels) in <top (required)>'

Finished in 0.60219 seconds
12 examples, 1 failure

Failed examples:

rspec ./spec/controllers/movies_controller_spec.rb:95 # MoviesController update should pass movie object the new attribute value to updated
Run Code Online (Sandbox Code Playgroud)

基本上它说我的最后一行测试失败了@fake_movie.should_receive(:update_attributes!).with("rating" => fake_new_rating).and_return(:true),我认为它根本没有收到函数调用'update_attributes!`,但为什么呢?

和控制器代码:

 def update
    @movie = Movie.find params[:id]
    @movie.update_attributes!(params[:movie])
    flash[:notice] = "#{@movie.title} was successfully updated."
    redirect_to movie_path(@movie)
  end
Run Code Online (Sandbox Code Playgroud)

提前致谢

Pau*_*l L 3

应该:

it 'should pass movie object the new attribute value to updated' do
  fake_new_rating = 'PG-15'
  Movie.stub(:find).and_return(@fake_movie)
  @fake_movie.should_receive(:update_attributes!).with("rating" => fake_new_rating).and_return(:true)
  put :update, :id => @fake_movie.id, :movie => {:rating => fake_new_rating}
end
Run Code Online (Sandbox Code Playgroud)

否则,该行将@movie = Movie.find params[:id]查询模型。

  • 作为一个好的实践,仅存根您拥有的内容,您不拥有“find”或“update_attributes”,您不应该存根它们 (2认同)