如何处理RSpec和Rails中的mock嵌套资源?

时间:2021-08-31 14:28:34

I've got a nested resource of User Reading Lists (a User has_many Reading Lists). I'm trying to mock everything in my controller specs, but having trouble keeping it concise. Here's the before code for the #show action:

我有一个用户阅读列表的嵌套资源(一个用户有很多阅读列表)。我试着模仿我的控制器规格中的所有东西,但是很难保持简洁。下面是#show action的前代码:

@reading_lists = mock("Reading lists")
@reading_lists.stub!(:find).with("1").and_return(@reading_list)
@user = mock_model(User, :reading_lists => @reading_lists)
User.stub!(:find).with("1").and_return(@user)
get :show, :user_id => "1", :id => "1"

which is testing:

这是测试:

def show
  @user = User.find(params[:user_id])
  @reading_list = @user.reading_lists.find params[:id]
end

This seems like a crazy amount of boilerplate - is there a better way to mock it out?

这似乎是一大堆样板文件——有更好的方式来模拟它吗?

1 个解决方案

#1


4  

There is not a better way to mock it out, but you are right to note that this is a lot of boiler plate. The reason is that user.reading_lists.find is a Law of Demeter violation. Whether or not you view the Law of Demeter as important, mocking through violations of it is painful.

没有更好的方法来模拟它,但是您应该注意到,这是大量的锅炉板。原因是user.reading_lists。发现是违反德墨特定律的。不管你是否认为迪墨特定律很重要,通过违反它来嘲笑它是很痛苦的。

I'd recommend either using the real models or simplifying the interaction with the model. I can't really say how without seeing what you're trying to specify.

我建议使用真实模型或者简化与模型的交互。我不知道你到底想说什么。

#1


4  

There is not a better way to mock it out, but you are right to note that this is a lot of boiler plate. The reason is that user.reading_lists.find is a Law of Demeter violation. Whether or not you view the Law of Demeter as important, mocking through violations of it is painful.

没有更好的方法来模拟它,但是您应该注意到,这是大量的锅炉板。原因是user.reading_lists。发现是违反德墨特定律的。不管你是否认为迪墨特定律很重要,通过违反它来嘲笑它是很痛苦的。

I'd recommend either using the real models or simplifying the interaction with the model. I can't really say how without seeing what you're trying to specify.

我建议使用真实模型或者简化与模型的交互。我不知道你到底想说什么。