2013-01-19 258 views
0

我是新来RSpec测试,我真的很感谢你的帮助。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 

回答

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响应。

+0

非常感谢! – user1993565

+0

不客气:) –

0

有一个很好的理由,这些查询都是很难在不属于他们有一个controller--测试。相反,最好将它们转移到您的模型上的任何一种课程方法或scopes,然后再通过控制器调用。然后你可以编写普通的RSpec model specs

请参见:How to test scopes?

+0

我知道它会更好,但由于某种原因,我正在使用的代码已经在控制器中,所以我现在就要这样离开它。感谢您的链接,请仔细阅读。 – user1993565