【问题标题】:rspec testing a controller post changing my params from symbols to strings and breaking my testsrspec 测试控制器后将我的参数从符号更改为字符串并破坏我的测试
【发布时间】:2010-02-02 10:47:37
【问题描述】:

在我的控制器规范中,我正在这样做:

it "should create new message" do
  Client.should_receive(:create).with({:title => 'Mr'})
  post 'create' , :client => {:title => "Mr" }
end

...在我的控制器中我正在做...

def create
  client = Client.create(params[:client])
end

但是,这失败了,并显示以下错误消息:

  expected: ({:title=>"Mr"})
       got: ({"title"=>"Mr"})

我想知道为什么会这样以及如何让它工作

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    这是因为您传递的是符号而不是字符串。这应该可以解决它:

    it "should create new message" do
      Client.should_receive(:create).with({:title => 'Mr'})
      post 'create' , :client => {"title" => "Mr" }
    end
    

    这是一篇关于它的博文:“Understanding Ruby Symbols

    【讨论】:

    • 你知道是否有可能让帖子将其作为符号传递,因为我想从机械师蓝图创建散列并且它们返回符号而不是字符串
    • 我不认为你可以做这样的事情,这只是 POST 的工作方式
    【解决方案2】:

    @ssmithone 您可以使用ActiveSupport::HashWithIndifferentAccess 将参数作为符号而不是字符串传递。这应该有效:

    it "should create new message" do
      Client.should_receive(:create).with({:title => 'Mr'}.with_indifferent_access)
      post 'create', :client => {:title => "Mr"}
    end
    

    【讨论】:

      猜你喜欢
      • 2016-12-10
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 2023-03-10
      相关资源
      最近更新 更多