Ruby-on-rails Rspec:测试实例变量的分配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4720135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rspec: testing assignment of instance variable
提问by jmccartie
Using Rspec with Factory Girl. Trying to check out what data is being assigned in my controller (and test against it). Every post I've read says I should be able to get something out of assigns() but it keeps returning nill
将 Rspec 与 Factory Girl 一起使用。试图检查我的控制器中分配了哪些数据(并对其进行测试)。我读过的每一篇文章都说我应该能够从assigns()中得到一些东西,但它一直返回nill
Controller
控制器
def index
@stickies = Sticky.where(:user_id => current_user.id)
end
Spec
规格
it "should assign stickies" do
foo = assigns(:stickies)
puts "foo = #{foo}"
end
Output
输出
foo =
Am I using the wrong syntax? Is there a better way to do this? Thanks!!
我使用了错误的语法吗?有一个更好的方法吗?谢谢!!
回答by David Chelimsky
You have to invoke the action first
你必须先调用动作
describe StickiesController do
describe "GET index" do
it "should assign stickies" do
get :index
assigns(:stickies).should_not be_nil
end
end
end
回答by Calin
If you are using the rspec > 2.99 you can use:
如果您使用的是 rspec > 2.99,则可以使用:
expect(assigns(:stickies)).not_to be_nil
expect(assigns(:stickies)).not_to be_nil

