Rspec将视图参数传递给控制器​​规范

时间:2015-12-12 01:14:55

标签: ruby-on-rails rspec rspec-rails

我的问题是我正在尝试使用rspec对我的方法进行尽可能多的覆盖,我无法测试一些特定的行。我试图在我的rspec中将params哈希传递给我的控制器方法,以模拟视图中的值。基本上,这些值将过滤结果以显示在我的索引页面上。

我正在测试的控制器方法是:

#sidebar h1, p em, p a:hover{ … }

我试图在我的rspec测试中传递params哈希。我尝试了几种方法,包括这个:

 def index
@buildings = Building.all

@buildings = @buildings.searchaddress(params[:searchaddress])


if params[:searchcompany] != nil
  @buildings = @buildings.searchcompany(params[:searchcompany][:management])
end

if params[:searchcompany] != nil
  @buildings = @buildings.searchcity(params[:searchcity][:city])
end

if params[:searchparking] == 'on'
  params[:searchparking] = 't'
  @buildings = @buildings.searchparking(params[:searchparking])
end

if params[:searchpets] != nil 
  params[:searchpets] = 't'
  @buildings = @buildings.searchpets(params[:searchpets])
end

searchpets,searchcompany等方法来自我的建筑模型,并实现为

describe "viewing all buildings" do
    it "renders index template" do

        param = Hash.new()
        param[:searchcompany] = [management:'asdf']
        param[:searchcity] = [city:'asdf']    #have also tried {city:""}
        param[:searchparking] = ['on']
        param[:searchpets] = [true]
        param[:searchaddress] = ['lalala']

        get :index, params:param #{searchcompany:{management:'asdf'}, searchcity:{city:'asdf'}, searchparking:'on', searchpets:true}
        expect(response).to render_template('index')
        expect(assigns(:buildings)).to be_truthy


        expect(Building).to receive(Building.searchcompany)
        expect(Building).to receive(Building.searchcity)
        expect(Building).to receive(Building.searchpets)
        expect(Building).to receive(Building.searchparking)
    end
   end

以下是我遇到的错误:

def self.searchaddress(search)
where("address LIKE ?", "%#{search}%") 
end

如何通过我的rspec测试将[:searchcity] [:city]传递给我的控制器方法?

1 个答案:

答案 0 :(得分:2)

你可以尝试:

 it "renders index template" do
    params = {
      searchcompany: {
        management: 'asdf'
      },
      searchcity: {
        city: 'asdf'
      },
      searchparking: 'on'
    }
    # All your expectations like 'expect(sth).to receive(:method)' go here
    get :index, params
    # Your remaining expectations go here
 end