我正在编写以下测试:
let!(:city_areas) { FactoryGirl.create_list(:city_area, 30) }
before {
@city_areas = mock_model(CityArea)
CityArea.should_receive(:where).and_return(city_areas)
}
it 'should assign the proper value to city areas variable' do
get :get_edit_and_update_vars
assigns(:city_areas).should eq(city_areas.order("name ASC"))
end
测试以下方法:
def get_edit_and_update_vars
@city_areas = CityArea.where("city_id = '#{@bar.city_id}'").order("name ASC").all
end
但是,它失败了,说 nil:NilClass 没有方法 'city_id',这让我相信它仍在尝试使用实例变量 @bar。
如何正确地删除此 where 语句以防止出现这种情况?
最佳答案
为什么你做 @city_areas = mock_model(CityArea) 然后你再也不用 @city_areas 了?
我会这样测试:
在模型 CityArea 中为此创建一个命名范围:where("city_id = '#{@bar.city_id}'").order("name ASC")
然后在你的 Controller 规范中做
describe 'GET get_edit_and_update_vars' do
before(:each) do
@areas = mock('areas')
end
it 'gets the areas' do
CityArea.should_receive(:your_scope).once.and_return(@areas)
get :get_edit_and_update_vars
end
it 'assign the proper value to city areas variable' do
CityArea.stub!(:your_scope => @areas)
get :get_edit_and_update_vars
assigns(:city_areas).should eq(ordered)
end
end
并且您还应该在模型规范上为该新范围创建一个规范
只是一个提示,你不应该在 before block 中使用 should_receive(...),使用 stub !在 before 里面,当你想测试调用该方法时使用 should_receive
此外,在测试 Controller 时你不应该使用 factorygirl,你应该总是模拟模型,模型可以在模型规范上进行测试
关于testing - Rspec:在 Controller 测试中删除 where 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12901860/