如何使用 rspec 测试搜索视图页面?
# 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
# 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 %>
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
assign
允许规范引用普通视图中预期的实例变量。@users
需要是一个数组,因此需要括号。注意:将问号替换为从
User.search
返回的任何类型的对象。编辑
嗯,这比乍一看要棘手。我找不到一种简单的方法来模拟一个可以响应必要消息以使该规范通过的对象。快速而肮脏的方法是只使用真实的对象:
缺点是这需要数据库连接才能工作。我们可以破解我们自己的辅助对象:
哪个适用于这个规范——但它适用于其他规范吗?
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:
The disadvantage is that this needs a database connection to work. We could hack up our own helper object:
Which works for this spec -- but will it work for others?