我进行了一组按姓名搜索导演的测试,这些测试或多或少对我有用。沿着:
describe MoviesController do
before :each do
@fake_results = [mock(Movie),mock(Movie)]
end
it "should call the model that looks for same director movies" do
Movie.should_receive(:find_by_same_director).with('Woody Allen').and_return(@fake_results)
post :find_by_same_director, {:name => 'Woody Allen'}
end
等等等等。这并没有令人震惊地破坏任何东西。不幸的是,我决定我需要更改我的控制器方法以获取 id 参数,而不是名称。我的代码的第二部分现在看起来像:
it "should call the model that looks for same director movies" do
Movie.should_receive(:find_by_same_director).with(:id => 1).and_return(@fake_results)
post :find_by_same_director, {:id => 1}
end
现在运行规范会导致以下错误:
1) MoviesController finding movies with same director should call the model method that looks for same director movies
Failure/Error: post :find_by_same_director, {:id => 1}
ActiveRecord::RecordNotFound:
Couldn't find Movie with id=1
# ./app/controllers/movies_controller.rb:62:in `find_by_same_director'
# ./spec/controllers/movie_controller_spec.rb:12:in `block (3 levels) in <top (required)>'
为什么没有 id = 1 的真实电影现在会导致严重错误 - 我的存根/模拟不再覆盖我了吗?以前没有伍迪艾伦导演的电影。我需要做什么才能让我的测试令人满意地假装 id 为 1 的电影存在?
编辑:
控制器动作如下:
def find_by_same_director
@movie = Movie.find params[:id]
@movies = Movie.find_same_director(@movie.id)
if @movies.count == 1
flash[:notice] = "'#{@movie.title}' has no director info"
redirect_to movies_path
end
end
不确定这是否需要哈希......?