Ruby JSON问题

时间:2012-03-23 11:25:31

标签: ruby cucumber sinatra capybara rack

我知道标题有点模糊,但我不知道该放什么。 我正在使用Sinatra开发一个用于Ruby后端的API。问题是我需要能够将JSON传递给代表用户的服务。 我面临的问题是,当我运行我的测试时它不起作用,但是对它所做的服务进行手动操作。我猜测JSON格式存在问题。

我已经更新了我的用户模型,以依赖ActiveModel中的帮助程序进行JSON序列化。我在手动转换时遇到了太多问题。这就是基本用户模型的样子:

class User
  include ActiveModel::Serializers::JSON
  attr_accessor :login, :email, :birthday, :created_at, :updated_at, :password_sha, :password_salt

  # Creates a new instance of the class using the information stored
  # in the hash. If data is missing then nill will be assigned to the
  # corresponding property.
  def initialize(params = {})
    return if params.nil?
    self.login = params[:login] if params.key?("login")
    self.email = params[:email] if params.key?("email")
    self.birthday = Time.parse(params[:birthday]) rescue Time.now
    if params.key?("password_salt") && params.key?("password_sha")
      self.password_salt = params["password_salt"]
      self.password_sha = params["password_sha"]
    elsif params.key?("password")
      self.set_password(params[:password])
    end
    self.created_at = Time.now
  end

  def attributes
    {:login => self.login, :email => self.email, :birthday => self.birthday, :created_at => self.created_at, :updated_at => self.updated_at, :password_sha => self.password_sha, :password_salt => self.password_salt}
  end

  def attributes=(params = {})
    self.login = params['login']
    self.email = params['email']
    self.birthday = params['birthday']
    self.created_at = params['created_at']
    self.updated_at = params['updated_at']
    self.password_sha = params['password_sha']
    self.password_salt = params['password_salt']
  end
end

我正在使用Cucumber,Rack :: Test和Capybara来测试我的API实现。 API应用程序的代码如下所示:

# This action will respond to POST request on the /users URI,
  # and is responsible for creating a User in the various systems.
  post '/users' do
    begin
      user = User.new.from_json(request.body.read)
      201
    rescue
      400
    end
  end

在上面的文章中,我期望请求体中的json表示。 由于某种原因,params哈希在这里是空的,不知道为什么 制作实际帖子的测试部分如下所示:

When /^I send a POST request to "([^\"]*)" with the following:$/ do |path, body|
  post path, User.new(body.hashes.first).to_json, "CONTENT_TYPE" => "application/json"
end

User.rb文件生成的示例输出JSON字符串如下所示:

"{"user":{"birthday":"1985-02-14T00:00:00+01:00","created_at":"2012-03-23T12:54:11+01:00","email":"arne.de.herdt@gmail.com","login":"airslash","password_salt":"x9fOmBOt","password_sha":"2d3afc55aee8d97cc63b3d4c985040d35147a4a1d312e6450ebee05edcb8e037","updated_at":null}}"

输出是从Rubymine IDE复制的,但是当我将其提交给应用程序时,我无法解析它,因为:

  • 使用测试时,params哈希是空的
  • 手动执行此操作会给我一个至少需要2个八位字节的错误。

0 个答案:

没有答案