简体   繁体   English

Rspec / rails:如何在视图中测试样本(x)

[英]Rspec/rails: How to test for sample(x) in a view

I have a home page that is pulling random entries from my db using this code (probably not the best way, but it works) 我有一个主页正在使用此代码从我的数据库中提取随机条目(可能不是最好的方法,但它可以工作)

def home
  ids = Entry.pluck(:id)
  @random_entries = Entry.find(ids.sample(5))
end

Here is the view: 这是视图:

<p>Here are 5 random entries:</p>
<% @random_entries.each do |entry| %>
<h3><%= entry.word.capitalize %></h3>
<p>Definition: <%= entry.definition %></p>
<% end %>

and so far my test is just: 到目前为止,我的测试只是:

it "should have the content 'Here are 5 random entries'" do
  visit '/'
  expect(page).to have_content('Here are 5 random entries')
end

But that test only checks for content that was hard-coded into the view. 但是该测试仅检查硬编码到视图中的内容。 The controller/view are working as I want them, but I have no test and not quite sure where to begin writing one for this. 控制器/视图正在按我的要求工作,但是我没有测试,也不太确定从哪里开始为此编写一个。

How should I be testing that controller action? 我应该如何测试控制器动作?

Maybe you could count the number of h3 tags that are present in the page like this: 也许您可以像这样计算页面中存在的h3标签的数量:

page.all('h3').count.should eql(5)

That will do if you don't have any other h3 tags anywhere else in that view. 如果您在该视图中的其他任何地方都没有其他任何h3标签,则可以这样做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM