我有两个型号:
class Solution < ActiveRecord::Base
belongs_to :owner, :class_name => "User", :foreign_key => :user_id
end
class User < ActiveRecord::Base
has_many :solutions
end
我在这样的用户中嵌套解决方案:
ActionController::Routing::Routes.draw do |map|
map.resources :users, :has_many => :solutions
end
最后这是我试图规定的行动:
class SolutionsController < ApplicationController
before_filter :load_user
def show
if(@user)
@solution = @user.solutions.find(params[:id])
else
@solution = Solution.find(params[:id])
end
end
private
def load_user
@user = User.find(params[:user_id]) unless params[:user_id].nil?
end
end
我的问题是,我如何确定@user.solutions.find(params[:id])
?
这是我目前的规格:
describe SolutionsController do
before(:each) do
@user = Factory.create(:user)
@solution = Factory.create(:solution)
end
describe "GET Show," do
before(:each) do
Solution.stub!(:find).with(@solution.id.to_s).and_return(@solution)
User.stub!(:find).with(@user.id.to_s).and_return(@user)
end
context "when looking at a solution through a user's profile" do
it "should find the specified solution" do
Solution.should_receive(:find).with(@solution.id.to_s).and_return(@solution)
get :show, :user_id => @user.id, :id => @solution.id
end
end
end
但是这给我带来了以下错误:
1)Spec::Mocks::MockExpectationError in 'SolutionsController GET Show, when looking at a solution through a user's profile should find the specified solution'
<Solution(id: integer, title: string, created_at: datetime, updated_at: datetime, software_file_name: string, software_content_type: string, software_file_size: string, language: string, price: string, software_updated_at: datetime, description: text, user_id: integer) (class)> received :find with unexpected arguments
expected: ("6")
got: ("6", {:group=>nil, :having=>nil, :limit=>nil, :offset=>nil, :joins=>nil, :include=>nil, :select=>nil, :readonly=>nil, :conditions=>"\"solutions\".user_id = 34"})
任何人都可以帮我解决@user.solutions.new(params[:id])
的问题吗?
答案 0 :(得分:25)
看起来我找到了自己的答案,但我会在这里发布,因为我似乎无法在网上找到很多这方面的内容。
RSpec有一个名为stub_chain的方法:http://apidock.com/rspec/Spec/Mocks/Methods/stub_chain
这样可以很容易地删除像:
这样的方法@solution = @user.solutions.find(params[:id])
通过这样做:
@user.stub_chain(:solutions, :find).with(@solution.id.to_s).and_return(@solution)
那么我可以这样写一个RSpec测试:
it "should find the specified solution" do
@user.solutions.should_receive(:find).with(@solution.id.to_s).and_return(@solution)
get :show, :user_id => @user.id, :id => @solution.id
end
我的规格通过了。但是,我还在这里学习,所以如果有人认为我的解决方案不好,请随意评论,我试着把它完全正确。
乔
答案 1 :(得分:11)
使用新的RSpec语法,您可以像这样存根链接
allow(@user).to receive_message_chain(:solutions, :find)
# or
allow_any_instance_of(User).to receive_message_chain(:solutions, :find)