如何使用rspec测试搜索视图页面?

时间:2011-02-17 03:38:26

标签: ruby-on-rails-3 rspec2

# encoding: utf-8
class UsersController < ApplicationController

  def index
    @search = User.search(params[:search])
    @users = @search.paginate :per_page => 20, :page => params[:page]
  end

end


<h2>User search</h2>
<%= form_for @search, :url => users_path, :html => { :method => :get } do |f| %>
#some form elements
<% end %>

<% @users.each do |user| %> 
# show user info
<% end %>

现在如何使用rspec 2测试视图?

# encoding: utf-8
require 'spec_helper'

describe "users/index.html.erb" do
  before(:each) do

    ####@user = stub_model(User)
            ######User.stub!(:search).and_return(@post)
      How to mock? If not mock(or stubed), it will got a nil error when rspec test.


  end

  it "renders a list of users" do
    render

    rendered.should contain("User search")
  end
end

1 个答案:

答案 0 :(得分:0)

it "renders a list of users" do
  assign(:search, stub_model(???)) # see note
  assign(:users, [stub_model(User)]
  render
  rendered.should contain("User search")
end

assign允许规范引用普通视图中预期的实例变量。 @users需要是一个数组,因此是括号。

注意:将问号替换为从User.search返回的任何类型的对象。

修改

这比乍一看时更难。我找不到一种简单的方法来模拟一个对象,该对象可以响应必要的消息以使该规范通过。快速而肮脏的方法是只使用一个真实的对象:

it "renders a list of users" do
  assign(:search, User.search)
  assign(:users, [stub_model(User)]
  render
  rendered.should contain("User search")
end

缺点是这需要数据库连接才能工作。我们可以破解我们自己的帮助对象:

class MetaSearchTestHelper
  extend ActiveModel::Naming
  include ActiveModel::Conversion
  attr_accessor :model_name
  def initialize(options={})
    @model_name = options[:model_name] || nil
  end
  def singular
    @model_name ? @model_name.downcase : nil
  end
  def persisted?
    false
  end
end

it "renders a list of users" do
  assign(:search, MetaSearchTestHelper.new(:model_name=>"User")
  assign(:users, [stub_model(User)]
  render
  rendered.should contain("User search")
end

哪个适用于此规范 - 但它是否适用于其他人?