Testing Rspec:在控制器测试中删除where语句

Testing Rspec:在控制器测试中删除where语句,testing,rspec,controller,Testing,Rspec,Controller,我正在编写以下测试: 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

我正在编写以下测试:

    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\u areas=mock\u model(cityrea),然后再也不使用@city\u areas

我会这样测试:

在模型CityArea中,为以下内容创建一个命名范围:where(“city_id=”{@bar.city_id}”).order(“name ASC”)

然后在你的控制器规范中你可以这样做

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块中使用should_receive(…),而应该使用stub!当您想测试调用该方法时,应在调用之前和使用之前接收


此外,在测试控制器时,您不需要使用factorygirl,您应该始终模拟模型,模型可以在模型规范上进行测试

是的,您的解决方案更干净了。谢谢你的帮助!