Moching Rails 关联方法
这是我想测试的辅助方法。
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 '[email protected]'
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>'
整个问题是 mocha 并没有真正模拟作者帖子的计数值,它返回 0 而不是 40。
有没有更好的方法可以做到这一点:@author.posts.expects(:count)。返回(40)?
Here is my helper method which I want to test.
def posts_correlation(name)
if name.present?
author = User.find_by_name(name)
author.posts.count * 100 / Post.count if author
end
end
A factory for user.
factory :user do
email '[email protected]'
password 'secret'
password_confirmation { password }
name 'Brian'
end
And finally a test which permanently fails.
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
Like this.
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>'
And the whole problem is that mocha doesn't really mock the count value of author's posts, and it returns 0 instead of 40.
Are there any better ways of doing this: @author.posts.expects(:count).returns(40)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您的辅助方法运行时,它会检索自己对作者的对象引用,而不是测试中定义的 @author。如果您要在辅助方法中
puts @author.object_id
和putsauthor.object_id
,您会看到此问题。更好的方法是将作者的设置数据传递到您的模拟记录中,而不是在测试对象上设置期望。
自从我使用 FactoryGirl 以来已经有一段时间了,但我认为这样的东西应该有效:
效率不是很高,但至少应该得到所需的结果,因为数据实际上会附加到记录中。
When your helper method runs, it's retrieving its own object reference to your author, not the @author defined in the test. If you were to
puts @author.object_id
andputs author.object_id
in the helper method, you would see this problem.A better way is to pass the setup data for the author in to your mocked record as opposed to setting up expectations on the test object.
It's been a while since I used FactoryGirl, but I think something like this should work:
Not terribly efficient, but should at least get the desired result in that the data will actually be attached to the record.