rspec测试控制器帖子将我的参数从符号改为字符串并破坏我的测试

时间:2010-02-02 10:47:38

标签: ruby-on-rails rspec

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

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"})

我想知道为什么会这样,以及如何让它发挥作用

2 个答案:

答案 0 :(得分:16)

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

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

以下是关于它的博文:“Understanding Ruby Symbols

答案 1 :(得分:2)

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

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