How to test a search view page with rspec?
# encoding: utf-8
class UsersCont开发者_StackOverflow社区roller < 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 %>
Now how to test view with 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
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
allows the spec to refer to the instance variables that would be expected in a normal view. @users
needs to be an array, thus the brackets.
Note: replace the question marks with whatever type of object gets returned from User.search
.
EDIT
Well this is trickier than it appears at first blush. I could not find an easy way to mock up an object that can respond to the necessary messages to get this spec to pass. The quick and dirty way is to just use a real object:
it "renders a list of users" do
assign(:search, User.search)
assign(:users, [stub_model(User)]
render
rendered.should contain("User search")
end
The disadvantage is that this needs a database connection to work. We could hack up our own helper object:
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
Which works for this spec -- but will it work for others?
精彩评论