新手关于Rails中Rspec测试的问题
我是 rspec 测试的新手。我对 Rails 中的 rspec 测试有两个问题。
如果我有一个“汽车”模型,它是一个ActiveRecord,
class Car < ActiveRecord::Base
...
def get_color
..
end
end
问题 1。 在 rspec 测试中(我已准备好所有宝石和配置) 之间有什么区别
before(:each) do
@my_car=Factory.create(:car, params)
end
,和
before(:each) do
@my_car=Car.new(params)
@my_car.save
end
(我的意思是在 rspec 测试范围内有什么区别,它们在 rspec 测试范围内没有相同的效果吗?不仅在 before(:each) do 内语句,而且还有describe...do语句)
问题2。正如你在我的汽车模型中看到的,有一个实例函数get_color
,我可以通过以下方式在 rspec 测试中调用此实例函数吗?
@my_car=Factory.create(:car, params)
@my_car.get_color #Can I call instance method in rspec test?
我已经尝试过这个,但实例方法似乎没有按照 rspec 测试中的预期返回结果。但可以在 rspec 测试代码之外工作,但我不确定。
谁能帮我解释一下这两个问题吗?
I am newbie in rspec test. I have two questions on rspec test in Rails.
If I have a 'Car' model which is an ActiveRecord,
class Car < ActiveRecord::Base
...
def get_color
..
end
end
Question 1. In rspec test (I have all the gems and configurations ready), what's the difference between
before(:each) do
@my_car=Factory.create(:car, params)
end
and
before(:each) do
@my_car=Car.new(params)
@my_car.save
end
(I mean what's the difference inside rspec test scope, dont they have the same effect inside rspec test? not only inside before(:each) do statement, but also describe...do statement)
Question 2. As you see in my car model, there is a instance function get_color
, can I invoke this instance function in my rspec test in the following way?
@my_car=Factory.create(:car, params)
@my_car.get_color #Can I call instance method in rspec test?
I have tried this, but it seems the instance method does not return the result as expected in rspec test. But works outside rspec test code, but I am not sure.
Anyone can makes me clear about the two questions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题1:
使用Factory Girl,这2种说法没有什么区别。使用 Factory Girl,您可以在创建对象期间拥有一些默认行为。在第二种情况下,您需要自己做。
问题2:
你需要测试你的方法。如果通过示例返回 0,您可以添加:
我们无法用更多代码更具体
Question 1 :
There are no difference between the 2 statement instead the using of Factory girl. With Factory girl you can have some default behavior during the creation of your Object. In the second case you need do it yourself.
Question 2 :
You need test your method. If by example return 0 you can add :
We can't be more specific with more code
Q1:实际上是一样的,尽管工厂更灵活,我更喜欢它们。
Q2:你可以执行@my_car.get_color,但仅仅执行它并没有任何意义。您要么需要检查它是否满足条件(可能使用应该),要么对其进行存根以返回您想要的值,而不实际执行(常见的 rspec 做法)。
Q1 : It's practically the same, though factories are more flexible and i prefer them.
Q2 : You can execute @my_car.get_color, but just executing it does not mean anything. You either need to check whether it fulfills a condition(using should probably) or stub it to return a value that you want, without actually executing(a common rspec practice).