随机失败的规格

时间:2015-08-11 12:42:13

标签: ruby-on-rails rspec

在我的Rails测试中,我有一个随机失败:

require 'spec_helper'
describe Api::V2::ClientsController, type: :controller do
  context 'happy path' do

    let!(:clients) {
      [create(:client), create(:client)]
    }

    it 'return authorized user resource in JSON format' do
      get :codes, format: :json

      expect(response).to be_success

      expect(json_response['clients'].size).to eql(2)

      expect(json_response['clients'][0]).to eql('code' => clients[0].code)
      expect(json_response['clients'][1]).to eql('code' => clients[1].code)
    end
  end
end

enter image description here

我不确定使用它:

let!(:clients) {
  [create(:client), create(:client)]
}

2 个答案:

答案 0 :(得分:2)

您可以尝试更换索引号(json_response [' clients'] [0])以获取不依赖于以正确顺序返回的json的内容。

例如:

clients.each do |client|
  expect(json_response['clients'].collect{|x|x['code']}).to include(client.code)
end

如果这样可以解决问题,您可能需要订购从控制器返回的客户端记录。

答案 1 :(得分:2)

我假设您的控制器没有按特定顺序(例如<ListView Name="lview" VerticalAlignment="Stretch" ItemsSource="{Binding Source={StaticResource ColoursSource}}"> </ListView> )获取记录,并且您的数据库也不保证任何默认顺序。

在这种情况下,您可以使用contains_exactly

<?php
$day_from = (isset($_POST['day_from']) ? $_POST['day_from'] : null);
$month_from = (isset($_POST['month_from']) ? $_POST['month_from'] : null);
$year_from = (isset($_POST['year_from']) ? $_POST['year_from'] : null);
$booking_from = $year_from."-".$month_from."-".$day_from;
$day_to = (isset($_POST['day_to']) ? $_POST['day_to'] : null);
$month_to = (isset($_POST['month_to']) ? $_POST['month_to'] : null);
$year_to = (isset($_POST['year_to']) ? $_POST['year_to'] : null);
$booking_to = $year_to."-".$month_to."-".$day_to;
$no_of_nights = abs(strtotime($booking_to) - strtotime($booking_from));     
$days = floor($no_of_nights / (60*60*24));

// create array with dates 
function daterange($booking_from, $booking_to, $step = '+1 day', $output_format = 'Y-m-d') {
 $dates = array();
 $first = new DateTime($booking_from);
 $last = new DateTime($booking_to);
 $interval = DateInterval::createFromDateString($step);
 $period = new DatePeriod($first, $interval, $last);

 foreach ($period as $date) {
  $dates[] = $date->format($output_format);
  }

   return $dates;
 }

 $dates = daterange($booking_from, $booking_to);

  print_r($dates);

  include 'connect.php';

  if (!$conn->autocommit(FALSE)) {
  printf("Errormessage: %s\n", $conn->error);
  }

  // loop thru dates and save in database table
  foreach ($dates as $date) {
  if (!$conn->query("INSERT INTO room_nights (bookingID, apartmentID, dates) VALUES (LAST_INSERT_ID(), '$apartment', '$date')")) {
  printf("Errormessage: %s\n", $conn->error);
 }
   }

 if (!$conn->commit()) {
 printf("Errormessage: %s\n", $conn->error);
}
$conn->close();

 ?>