我是 Rails 的新手,我正在尝试使用 rspec 测试 Controller 。我的第一个测试是在调用 show 操作时,它应该通过 url 查找类别。
问题是当我添加 stub 代码时,出现以下错误:
# 的未定义方法“查找”
我的测试是这样的:
require 'spec_helper'
describe CategoriesController do
describe "GET /category-name/" do
before(:each) do
@category = mock_model(Category)
Category.stub!(:find).with(:first, :conditions => ["url = :url", {:url => "category-name"}]).and_return(@category)
end
it "should find the category by url" do
controller.show
Category.should_receive(:find).with(:first, :conditions => ["url = :url", {:url => "category-name"}]).and_return(@category)
end
end
end
最佳答案
您对请求的调用应该在任何 should_receive
之后。这是一件紧张的事情。所以它有点像这样读,“当发生这种情况时,类别应该接收一些东西”。 “这发生了”指的是请求。
it "should find the category by url" do
Category.should_receive(:find).with...
get "show", { your params, if you're sending some in }
end
此外,至少对于这个特定的测试,您想要采用请求方式而不是调用 Controller 方法本身。
所以
post "action_name"
get "action_name"
update "action_name"
delete "action_name"
代替
controller.action_name
关于ruby-on-rails - 使用 rspec 测试 Rails Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2352985/