Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rspec:存根关系查找(链)_Ruby On Rails_Rspec - Fatal编程技术网

Ruby on rails Rspec:存根关系查找(链)

Ruby on rails Rspec:存根关系查找(链),ruby-on-rails,rspec,Ruby On Rails,Rspec,控制器: @organization.topics.find(params[:id]) 如何使用Rspec将其存根到控制器规格中?(@organization正在my spec helper中设置) 我试过: controller.stub_chain(:topics, :find).with("37") { mock_topic } Topic.stub(:find).with("37") { mock_topic } 上述两项似乎都不起作用。有什么想法吗?谢谢 你就不能: @organi

控制器:

@organization.topics.find(params[:id])
如何使用Rspec将其存根到控制器规格中?(
@organization
正在my spec helper中设置)

我试过:

controller.stub_chain(:topics, :find).with("37") { mock_topic }
Topic.stub(:find).with("37") { mock_topic }
上述两项似乎都不起作用。有什么想法吗?谢谢

你就不能:

@organizations.topics.stub!(:find).and_return(mock_whatever)

如果您有权访问
@organization
变量(您表示有权访问),那么您应该能够:

@organization.stub_chain(:topics, :find).and_return(mock_topic)
我不相信(除非他们将API更改为stub\u-chain,但我在文档中没有看到任何这种性质的东西)在使用stub\u-chain时可以指定.with('37')。如果绝对有必要指定传递给find方法的变量(这种情况很少发生),则必须采取长路径:

# This line is attempting to fake-out the .topics association and
# just return a mock of *whatever*, since it's just an intermediary
# step to where we really want to get to.
topics = @organizations.stub!(:topics).and_return(mock_model(Topic))
topics.stub!(:find).with('37').and_return(mock_topic)

这与mock_model(Topic,:id=>37)结合起来应该可以工作。如果打算同时存根对.topics的调用,那么这将不起作用。True,但是您可以有一个期望调用:find的mock。