如何在 Rails 模型的构造函数中使用参数
我尝试使用 RSpec 学习 tdd。我从网上找到的备忘单中获取了这个示例,但对于如何实现它有点困惑。添加 MovieList.new 是自动的,但是当 ActiveRecord 已处理该参数时,我将如何添加参数。然后添加“forward”方法。
describe "forward" do
it "should jump to a next movie" do
next_movie = MovieList.new(2).forward
next_movie.track_number.should == 2
end
end
I trying to learn tdd using RSpec. I took this example from a cheat sheet I found online and am a bit confused as to how I would implement it. To add MovieList.new is automatic but how would I go about adding a parameter when it is already handled with ActiveRecord. And then to add the 'forward' method as well.
describe "forward" do
it "should jump to a next movie" do
next_movie = MovieList.new(2).forward
next_movie.track_number.should == 2
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果这是对 MovieList 类的测试,请创建一个名为 MovieList 的类。
然后在该类的构造函数中,确保它接受一个名为 track_number 的参数,在测试中它是 2。
然后创建一个名为forward 的方法来执行您需要它执行的任何操作?
这是我要这样做的一个很好的例子:
http://rspec.info/
这听起来可能模棱两可,但问题也是如此。
编辑:
这是如何创建新的 MovieList 类并使用名为 track_number 的参数对其进行初始化的粗略想法。
If this is a test for a MovieList class, create a class called MovieList.
Then in your constructor for that class, make sure it takes in a parameter called track_number, in your test that's the 2.
Then create a method called forward to do whatever you need it to do?
Here's a good example of where I'm going with this:
http://rspec.info/
This may sound ambiguous, but so was the question.
EDIT:
This is a rough idea of how to create a new MovieList class and initialize it with a parameter called track_number.
我不确定forward在你的例子中做了什么,因为你似乎将track_number初始化为2然后调用forward。我本来期望 track_number 增加,但你的测试正在检查它是否仍然是 2。
请注意,我不认为您需要更改构造函数来获取参数,只要您将其作为哈希传递(我的示例中隐含了单个成员哈希)...有人可以验证或反驳最后一个断言吗?
I am not sure what forward does in your example because you seem to be initializing track_number to 2 then calling forward. I would have expected track_number to increment but your test is checking to see if it's 2 still.
Note, I don't believe you need to change your constructor to take the parameter as long as you pass it in as a hash (the single member hash is implied in my example)...can someone verify or refute this last assertion?