Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails测试正在将我的int数组转换为字符串数组_Ruby On Rails_Ruby_Post_Minitest - Fatal编程技术网

Ruby on rails Rails测试正在将我的int数组转换为字符串数组

Ruby on rails Rails测试正在将我的int数组转换为字符串数组,ruby-on-rails,ruby,post,minitest,Ruby On Rails,Ruby,Post,Minitest,我对控制器上的create方法进行了以下测试 before :each do request.env["HTTP_ACCEPT"] = 'application/json' request.env["CONTENT_TYPE"] = "application/json" end test "should post create" do params = { trip_id: 1, schedule: { price:

我对控制器上的create方法进行了以下测试

  before :each do
    request.env["HTTP_ACCEPT"] = 'application/json'
    request.env["CONTENT_TYPE"] = "application/json"

  end

  test "should post create" do
    params = {
      trip_id: 1,
      schedule: {
        price: 12.50,
        max_size: 1,
        time: "11:00 am",
        wdays: [0,1]
      }
    }

    post :create, params
    assert_response :success
  end
当点击我的创建方法时,参数[:schedule][:wdays]从[0,1]更改为[“0”,“1”]

这导致我的测试失败,因为wday必须是int数组。我想在我的验证中做一个.to_I,但这将允许[“hello”,“world”]变成[0,0]

奇怪的是,这个curl命令,我认为它也会做同样的事情,工作得很好

curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"trip_id":1, "schedule":{"price":12.50,"max_size":1,"wdays":[0,1],"time":"11:00 am"}}' http://localhost:3000/trips/1/schedules
如何让我的测试将数组保留为类似于curl中的int数组?

如果我无法让此功能在测试中正常工作,我是否应该更改验证以允许一系列数组?如果我这样做,我应该如何防止像“hello”这样的字符串有效?

这是我当前的验证:

  def valid_wdays
    if !wdays.is_a?(Array) || wdays.detect { |d| !(0..6).include?(d) }
      errors.add(:wdays, "should be an array of ints represeting days of the week")
    end
  end

您需要指定请求不仅接受JSON(
-H“Accept:application/JSON”
在curl中,
request.env[“HTTP_Accept”]='application/JSON'
在测试中),而且以JSON的形式发送数据(
-H“Content type:application/JSON”
在curl中,测试中没有任何内容)

试试像这样的东西

post :create, params.to_json, format: :json


您应该记住HTTP参数只支持字符串。那么为什么curl可以工作呢?这在curl中可以工作,因为curl使用rails堆栈来处理请求。您的控制器测试绕过了整个rails堆栈,基本上对所有内容调用
.to_param
。集成测试会给你带来更好的运气,因为它实际上使用了ActionDispatch。那么这是否意味着我不能在这里测试这条路线?@bsiddiqui你可以在任何地方做任何事情。尝试将此类添加到测试中,并在参数中使用它:
wdays:[IntParam.new(0),IntParam.new(1)]
-
class IntParam;def初始化int@int=int;结束;def至_参数@int;结束;结束
post :create, params.to_json, {'CONTENT_TYPE' => 'application/json'}