使用 Rspec 开始我的 TDD 之旅并遇到一些问题。不明白为什么我的 rspec 在 if ... OR 条件下失败。
def director
@movie = Movie.find_by_id(params[:id])
if @movie.nil? or @movie.director.empty?
flash[:notice] = "The movie has no director info"
redirect_to movies_path
else
# success
end
end
Rspec 测试:
before ... #stubs
it 'assigns movies array in director action' do
Movie.stub(:find_by_id).and_return(@movie)
get "director", :id => 1
...
end
错误:
1) MoviesController assigns movies array in director action
Failure/Error: get "director", :id => 1
NoMethodError:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.empty?
如果没有找到记录,那么@movie.nil?应该满足条件和@movie.director.empty?不应该评估;那是对的吗?
在这种情况下,我不在乎是否没有这样的记录或请求记录的主管字段为空白,我会以同样的方式处理。
感谢你的帮助。
更新
我已经将一些控制器的东西删除到模型中,如下所示:
控制器:
def director
@movies = Movie.same_director_by_id(params[:id])
if @movies.blank?
redirect_to movies_path
end
end
电影:
def self.same_director_by_id (id)
movie = self.find_by_id(id)
if movie.nil? or movie.director.blank?
return []
else
return self.where("id != ?", id).find_all_by_director(movie.director)
end
end
规格:
it 'assigns movies array in director action' do
Movie.should_receive(:same_director_by_id).and_return([@movie])
get "director", :id => 1
assigns(:movies).should be_kind_of(Array)
end
现在所有控制器规格都完美通过了。我将单独测试模型。
更新 2:
问题是我在模型上存根 :director,而不是在模拟上!呼吸暂停是正确的。