RSpec View 测试:如何修改参数? [英] RSpec View testing: How to modify params?
问题描述
我正在尝试使用 RSpec 测试我的视图.给我带来麻烦的特定视图会根据 url 参数改变其外观:
link_to "sort>name", model_path(:sort_by => 'name')
导致 http://mydomain/model?sort_by=name
我的视图然后像这样使用这个参数:
<% if params[:sort_by] == 'name' %><div>按名称排序</div><%结束%>
RSpec 如下所示:
它应该告诉用户排序的属性"做#问题:分配参数[:sort_for] = 'name'呈现/groups/index.html.erb"response.should have_tag("div", "按名称排序")结尾
我想在 RSpec 中测试我的视图(没有控制器),但我无法将此参数放入我的 params
变量中.我尝试了所有不同风格的 assign
:
assign[:params] = {:sort_by =>'名字'}
assign[:params][:sort_by] = 'name'
- ...
目前没有成功.每个想法都值得赞赏.
那是因为您不应该在视图中使用 params
.
我认为使用助手的最佳方式.
Sorted by <%= sorted_by %>
并在您的帮助文件之一中
def sorted_byparams[:sorted_by].capitalize结尾
然后你可以很容易地测试你的助手(因为在助手测试中,你可以定义 params
请求.
I am trying to test my views with RSpec. The particular view that is causing me troubles changes its appearance depending on a url parameter:
link_to "sort>name", model_path(:sort_by => 'name')
which results in http://mydomain/model?sort_by=name
My view then uses this parameter like that:
<% if params[:sort_by] == 'name' %>
<div>Sorted by Name</div>
<% end %>
The RSpec looks like this:
it "should tell the user the attribute for sorting order" do
#Problem: assign params[:sort_for] = 'name'
render "/groups/index.html.erb"
response.should have_tag("div", "Sorted by Name")
end
I would like to test my view (without controller) in RSpec but I can't get this parameter into my params
variable. I tried assign
in all different flavours:
assign[:params] = {:sort_by => 'name'}
assign[:params][:sort_by] = 'name'
- ...
no success so far. Every idea is appreciated.
That's because you shouldn't be using params
in your views.
The best way I see it to use an helper.
<div>Sorted by <%= sorted_by %></div>
And in one of your helper files
def sorted_by
params[:sorted_by].capitalize
end
Then you can test your helpers quite easily (because in helpers tests, you can define the params
request.
这篇关于RSpec View 测试:如何修改参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!