[英]Testing an Rspec Controller with associations
I've got two models: 我有两个模型:
class Solution < ActiveRecord::Base
belongs_to :user
validates_attachment_presence :software
validates_presence_of :price, :language, :title
validates_uniqueness_of :software_file_name, :scope => :user_id
has_attached_file :software
end
class User < ActiveRecord::Base
acts_as_authentic
validates_presence_of :first_name, :last_name, :primary_phone_number
validates_uniqueness_of :primary_phone_number
has_many :solutions
end
with my routes looking like this: 我的路线如下所示:
map.resources :user, :has_many => :solutions
Now I'm trying to test my solutions controllers with the following RSpec test: 现在,我正在尝试使用以下RSpec测试来测试我的解决方案控制器:
describe SolutionsController do
before(:each) do
@user = Factory.build(:user)
@solution = Factory.build(:solution, :user => @user)
end
describe "GET index" do
it "should find all of the solutions owned by a user" do
Solution.should_receive(:find_by_user_id).with(@user.id).and_return(@solutions)
get :index, :id => @user.id
end
end
end
However, this gets me the following error: 但是,这使我遇到以下错误:
ActionController::RoutingError in 'SolutionsController GET index should find all of the solutions owned by a user'
No route matches {:id=>nil, :controller=>"solutions", :action=>"index"}
Can anybody point me to how I can test this, since the index should always be called within the scope of a particular user? 谁能指出我该如何进行测试,因为索引应始终在特定用户的范围内调用?
Factory#build
builds an instance of the class, but doesn't save it, so it doesn't have an id yet. Factory#build
会构建该类的实例,但是不会保存它,因此它还没有ID。
So, @user.id
is nil because @user
has not been saved. 因此, @user.id
为nil,因为尚未保存@user
。
Because @user.id
is nil, your route isn't activated. 由于@user.id
为nil,因此您的路由未激活。
try using Factory#create
instead. 尝试改用Factory#create
。
before(:each) do
@user = Factory.create(:user)
@solution = Factory.create(:solution, :user => @user)
end
Looks like your other problem is on this line: 看来您的其他问题在此行上:
get :index, :id => @user.id
You're trying to make a request to the index method, but you've provided the wrong variable name. 您正在尝试向index方法发出请求,但是您提供了错误的变量名。 When testing SolutionsController
id
implies a solution id, you need to supply the user id. 当测试SolutionsController
id
暗示解决方案ID时,您需要提供用户ID。 This should work, or at least move you forward: 这应该起作用,或者至少使您前进:
get :index, :user_id => @user.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.