如何编写 rspec 以根据指定的日期范围过滤帖子 [英] How to write rspec for filtering the posts based on specified date range

查看:32
本文介绍了如何编写 rspec 以根据指定的日期范围过滤帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的博客应用程序,用户可以在其中根据日期范围(开始日期和结束日期)过滤帖子.我使用 AJAX 调用在索引页面中显示帖子.一旦用户使用两个日期选择器给出日期范围并单击提交按钮,就会进行 AJAX 调用并显示过滤后的帖子.开发方面没有问题,但在测试的情况下,我不知道如何进一步进行.但我的目标是检查索引页面中显示的帖子是否在指定的日期范围内.我已经包含了 post 控制器中定义的 datefilter 操作:

I have a simple blog application where the user can able to filter the post based on the date range (start_date & end_date).I have used AJAX call for displaying the post in the index page. Once the user give the range of date using two date pickers and click on submit button the AJAX call is made and the filtered posts will be displayed.There is no problem in the development side but in case of testing I dont know how to proceed further.But my objective is to check weather the posts displayed in the index page are within the specified date range. I have included the datefilter action defined in the post controllers:

def dateFilter
    if (params[:start_date].present? )&& (params[:end_date].present?)
      if Time.parse(params[:start_date])<=Time.parse(params[:end_date])&& (Time.parse(params[:start_date])<= Date.today)&& (Time.parse(params[:end_date])<= Date.today)
        @start_date= params[:start_date].to_date.beginning_of_day
        @end_date=params[:end_date].to_date.end_of_day
      else
        @error = true
      end
    else
      @start_date= Date.yesterday.beginning_of_day
      @end_date=Date.today.end_of_day
    end
    @posts= Post.date_filter(@start_date,@end_date)
  end

在索引页面中,我使用了日期选择器,如下所示:

In the index page I have used the datepicker as follows:

 <%= form_tag({:controller => 'posts', :action => 'dateFilter'},remote: true) do %>
    <%=  date_field_tag 'start_date' %>
    <%=  date_field_tag 'end_date' %>
    <%= submit_tag 'Submit' %>
    <% end %>
  <% end %>

当进行 AJAX 调用时,它会将帖子呈现为 js 文件 datefilter.js.erb

when the AJAX call is made it renders the posts as a js file datefilter.js.erb

<% if @error==true %>
alert("enter correct date format");
<% elsif @posts.blank? %>
alert("No posts in the given date");
<%else %>
$('.post_div').html('<%= j render @posts %>')
<% end %>
$('#page').hide()

帮助我为上述场景编写 rspec

Help me in writing rspec for the above scenario

推荐答案

您可以使用具有指定日期的 before 操作创建多个帖子,并在您知道具有指定帖子数的日期范围内调用控制器操作并检查帖子数回复中的预期帖子

You can create multiple posts using before action with specified dates and call the controller action with a date range you know to have specified number of posts and check the count of the expected posts in the response

例如

@post1 = FactoryBot.create(:post, start_date: DATE) 
@post2 = FactoryBot.create(:post, start_date: DATE) //Using Factory

let(:data) = {
start_date: Date,
end_date: Date}

get:CONTROLLER_ACTION params: data 

然后根据您的要求期待响应

Then expect the response as per your requirement

这篇关于如何编写 rspec 以根据指定的日期范围过滤帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆