Fas*_*ian 1 rspec ruby-on-rails view-helpers
我想实现一个类似于 stackoverflow 的标签系统,右上角有一个带有标签的框,而且我还有从 params 哈希中删除标签的链接。我的方法在浏览器中运行正常。但我找不到方法来测试它。
def tags_list_with_destroy_links
if params[:tags]
li = ""
p = params[:tags].split("+") # '/tagged/sea+ship+sun' => ['sea', 'ship', 'sun']
p.map do |t|
remove_link = if p.count >= 3
c = p.reject {|item| item == t }
a = c.join("+")
{:tags => a}
elsif p.count == 2
c = p.reject {|item| item == t }
{tags: c[0]}
else
questions_url
end
li << content_tag(:li) do
link_to(t, questions_tags_path(t), class: 'tag') +
link_to( '', remove_link , class: 'icon-small icons-cross')
end
end
ul = content_tag(:ul, li.html_safe)
ul << tag(:hr)
end
end
Run Code Online (Sandbox Code Playgroud)
我试过了:
it 'return list with selected tags' do
#Rails.application.routes.url_helpers.stub(:questions_tags).and_return('/questions/tagged/sea+ship+sun')
#helper.request.stub(:path).and_return('/questions/tagged/sea+ship+sun')
helper.stub(:url_for, {controller:'questions', action: 'index', tags:'sea+ship+sun'} ).and_return('/questions/tagged/sea+ship+sun')
helper.params[:tags] = 'sea+ship+sun'
helper.tags_list_with_destroy_links.should == 'list_with_tags'
end
Run Code Online (Sandbox Code Playgroud)
但它返回:
<a class=\"tag\" href=\"/questions/tagged/sea+ship+sun\">sea</a><a class=\"icon-small icons-cross\" href=\"/questions/tagged/sea+ship+sun\"></a></li>
Run Code Online (Sandbox Code Playgroud)
并应返回删除链接作为
href="/questions/tagged/ship+sun" 没有海
如果有任何建议,我将不胜感激
params 字段将被解析为正确的 ruby 数据结构(哈希、数组、字符串等)。无需手动拆分项目,例如+,如果有嵌套参数,它将作为 params 对象的一部分返回:
{tags: ["sea", "ship", "sun"]}
Run Code Online (Sandbox Code Playgroud)
要访问您的数据,或创建有关测试中存在的参数数据的假设,您需要创建一个存根。你就快到了,尝试更多类似的事情:
helper.stub!(:params).and_return({tags: ["sea", "ship", "sun"]})
Run Code Online (Sandbox Code Playgroud)
一旦正确存根了参数,您就可以检查辅助方法的输出以确保其有效性(这称为期望):
expect(helper.tags_list_with_destroy_links).to eq("some_url")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3789 次 |
| 最近记录: |