Ruby on rails Moching-rails关联方法
这是我想测试的助手方法Ruby on rails Moching-rails关联方法,ruby-on-rails,factory-bot,mocha.js,testunit,Ruby On Rails,Factory Bot,Mocha.js,Testunit,这是我想测试的助手方法 def posts_correlation(name) if name.present? author = User.find_by_name(name) author.posts.count * 100 / Post.count if author end end 供用户使用的工厂 factory :user do email 'user@example.com' password 'secret' pass
def posts_correlation(name)
if name.present?
author = User.find_by_name(name)
author.posts.count * 100 / Post.count if author
end
end
供用户使用的工厂
factory :user do
email 'user@example.com'
password 'secret'
password_confirmation { password }
name 'Brian'
end
最后是一个永远失败的测试
test "should calculate posts count correlation" do
@author = FactoryGirl.create(:user, name: 'Jason')
@author.posts.expects(:count).returns(40)
Post.expects(:count).returns(100)
assert_equal 40, posts_correlation('Jason')
end
像这样
UsersHelperTest:
FAIL should calculate posts count correlation (0.42s)
<40> expected but was <0>.
test/unit/helpers/users_helper_test.rb:11:in `block in <class:UsersHelperTest>'
UsersHelperTest:
失败应计算职位计数相关性(0.42s)
这是意料之中的事,但事实并非如此。
test/unit/helpers/users\u helper\u test.rb:11:in'block in'
整个问题是mocha并没有真正模拟作者帖子的计数值,它返回0而不是40
有没有更好的方法:
@author.posts.expected(:count).returns(40)
?当您的助手方法运行时,它将检索自己对作者的对象引用,而不是测试中定义的@author。如果您在helper方法中放置@author.object\u id和放置author.object\u id
,您会看到这个问题
更好的方法是将作者的设置数据传递到模拟记录中,而不是在测试对象上设置期望值
我已经有一段时间没有使用FactoryGirl了,但我认为这样的方式应该可以:
@author = FactoryGirl.create(:user, name: 'Jason')
(1..40).each { |i| FactoryGirl.create(:post, user_id: @author.id ) }
效率不太高,但至少应该得到所需的结果,因为数据将实际附加到记录。如果这样做会怎么样:
author.stubs(:posts).returns(stub(:count=>40))
。也就是说,短链在RSpects中处理得更好。这会起作用的,是的。但我更喜欢用摩卡咖啡做更多的事情,而不需要在数据库中创建40条额外的记录。有办法吗?我还尝试将这一行添加到我的测试User.expected(:find_by_name)。with(anything)。returns(@author)
,但它没有帮助通过。这是因为当它调用@author.posts时,posts将再次成为与测试中模拟的对象不同的对象。如果需要模拟任何内容,请给@author一个mock posts对象,比如@author.expected(:posts).returns(['dummy']*40)
,而不是模拟对posts对象的调用。