我正在尝试在我的控制器中测试自定义搜索方法的行为:
#RecordingsController
def search
# raise params.inspect
@search = params[:search]
searches = []
searches2 = []
for n in 1..5
searches << @search["date(#{n}i)"].to_i
searches2 << @search["date2(#{n}i)"].to_i
end
start_date = date_format(*searches)
end_date = date_format(*searches2)
conditions = []
conditions << "agent like '%#{@search["agent"]}%'" unless @search["agent"].blank?
conditions << "phone like '%#{@search["phone"]}%'" unless @search["phone"].blank?
conditions << "date between '#{start_date}' and '#{end_date}'"
@recordings = Recording.where(conditions.join(" AND ")).order('date ASC')
if @recordings.blank?
redirect_to("/", alert: "No results were found for this search. Please try again.")
else
render "recordings/search"
end
end
使用以下布局:
#recordings_controller_spec.rb
describe RecordingsController do
describe "POST #search" do
context "with valid attributes" do
it "assigns a new search to @search" do
search = @recording_search
get :search, @recording_search
assigns(:search).should eq(search)
end
it "populates an array of recordings"
it "renders the :search view"
end
end
end
我得到的最远的是尝试构建一个哈希来模仿我的 params 哈希将用于表单
#params hash
params = {"search" => { "date_1i" => "2012", "date_2i" => "1", ... "date2_5i" => "00" } }
其中 date_#{n}i 是开始日期 [年、月、日、小时、分钟],而 date2_#{n}i 是结束日期。我正在尝试遵循此处发布的答案,仅使用常规哈希来模仿 params 哈希。正如您从我的控制器中看到的那样,我实际上并没有将参数传递给我的#search 方法。我可以做?或者有没有办法在 rspec 测试中模拟 params 哈希并确定我@search
的@recordings
、 和redirect_to
/render
变量/操作是否正在执行?我已经在我的请求规范中测试了渲染/重定向,但如果可以的话,我想全面测试这个方法。