testing - Rspec:在 Controller 测试中删除 where 语句

标签 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 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/

相关文章:

java - 哪个 BDD 框架允许对 "story writing"采取简单的方法?

ruby - 如何测试一个元素是从列表中随机选择的?

ruby-on-rails - 接收(:创建)的 Controller 规范 : expect(controller). 阻止执行#create 操作

java - 在 JSP 中显示本地磁盘镜像(Web 上下文之外的镜像)

scala - Scala 测试中应该和必须有什么区别?

testing - 协议(protocol)栈开发的嵌入式测试

android - Android : Suggestions for test application 蓝牙开发入门

ruby-on-rails - RSpec 在 controller_spec 中将对象作为参数传递

ruby-on-rails - spork 0.9.2 和 rspec 3.0.0 = 未初始化常量 RSpec::Core::CommandLine (NameError)

java - 如何在请求正文中将 map 从 Angular 客户端正确发送到 Spring Boot Controller ?收到的 map 总是空的