0

我是使用 RSpec 测试的新手,非常感谢您的帮助。

这是我在控制器内的索引操作,我需要对其进行测试,以查看视图内的链接选择是否按预期运行。我会很感激你能提供给我的任何代码,因为我什至不知道从哪里开始。

def index
 respond_to do |format|
  format.html
  format.json do
    if params[:s_id].blank? && !params[:f_id].blank?
      @fp_for_dropdown = Model.where(:f_id => params[:f_id])
    elsif !params[:s_id].blank? && params[:f_id].blank?
      @fp_for_dropdown = Model.where(:s_id => params[:s_id])
    elsif !params[:s_id].blank? && !params[:f_id].blank?
        @fp_for_dropdown = Model.where(:s_id => params[:s_id], :f_id => params[:f_id])
    else
      @fp_for_dropdown = Hash[]
    end
    render :json => Hash["" => ""].merge(Hash[@fp_for_dropdown.map { |i| [i.id, i.name] }])
  end
end

结尾

4

2 回答 2

0

这些查询很难在控制器中测试是有充分理由的——它们不属于那里。相反,最好将它们移动到模型上的类方法或作用域中,然后从控制器调用它们。然后您可以编写常规的 RSpec模型规范

请参阅:如何测试范围?

于 2013-01-19T22:02:59.223 回答
0

解决此问题的一种方法是将控制器测试视为单元测试。这意味着模拟对 Model 的调用以确保调用正确的调用。

describe SomeController do
  it 'should retrieve by s_id only' do
    Model.should_receive(:where).with(:s_id => 'abc')
    get :index, :s_id => 'abc'
  end
  it 'should retrieve by f_id only' do
    Model.should_receive(:where).with(:f_id => 'abc')
    get :index, :f_id => 'abc'
  end
  it 'should retrieve by f_id and s_id' do
    Model.should_receive(:where).with(:f_id => 'abc', :s_id => '123')
    get :index, :f_id => 'abc', :s_id => '123'
  end
  it 'should not hit the database without f_id or s_id' do
    Model.should_not_receive(:where)
    get :index
  end
end

如果你想看中,你也可以测试响应json:

it 'should retrieve by f_id only' do
  Model.should_receive(:where).with(:f_id => 'abc').and_return(OpenStruct.new(id: 'abc', name: '123'))
  get :index, :f_id => 'abc'
  JSON.parse(response.body).should == {} # INCOMPLETE, fill in response to expect
end

不幸的是,我无法完成响应检查,因为我不知道你在用这一行中的哈希做什么:

render :json => Hash["" => ""].merge(Hash[@fp_for_dropdown.map { |i| [i.id, i.name] }])

查看jbuilderrabl以使用视图构建 JSON 响应。

于 2013-01-19T22:09:27.893 回答