我的模型:
class Post < ActiveRecord::Base
#...
def my_method
{:created_at => self.created_at, :words => self.text.split.find_by{/*my_conditiond_here*/}}
end
#...
end
控制器:
class TasksController < ApplicationController
#...
def my_action
posts = Post.where(params[:conditions])
@words = posts.map{|post| post.my_method}.flatten
end
#...
end
但是当我尝试对其进行测试时,我遇到了一些麻烦。
it "returns words for single post" do
post = FactoryGirl.create :post, :text => 'any text here'
get :my_action
expect(assigns[:words]).to eq(post.my_method)
end
我得到类似的东西:
expected: [{:words=>["any", "text", "here"], :created_at=>2013-11-12 09:33:04 UTC}] got: [{"words"=>["any", "text", "here"], "created_at"=>2013-11-12 09:33:04 UTC}]
不仅如此,如果我使用
expect(assigns[:words].first).to eq(post.my_method.fitst.with_indifferent_access)
它失败:
expected: {"words"=>["any", "text", "here"], "created_at"=>2013-11-12 09:33:04 UTC} got: {"words"=>["any", "text", "here"], "created_at"=>2013-11-12 09:33:04 UTC} (compared using ==) Diff:
通过实验,我意识到了这个问题created_at
元素中的问题。
看起来可以存根my_method
,但我不知道如何返回连接到对象的值。例如身份证。或者建议请更好的测试方法my_action
。