:user_id end class User :solutions end 最后,这是我正在尝试规范-6ren">
gpt4 book ai didi

ruby-on-rails - RSpec, stub 嵌套资源方法

转载 作者:行者123 更新时间:2023-12-04 00:03:41 25 4
gpt4 key购买 nike

我有两个模型:

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"})

任何人都可以帮助我如何 stub @user.solutions.new(params[:id]) ?

最佳答案

看起来我找到了我自己的答案,但我要把它贴在这里,因为我似乎无法在网上找到很多关于这个的信息。

RSpec 有一个名为 stub_chain 的方法:http://apidock.com/rspec/Spec/Mocks/Methods/stub_chain

这使得 stub 方法很容易,例如:

@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

我的规范通过了。但是,我仍然在这里学习,所以如果有人认为我在这里的解决方案不好,请随时对此发表评论,我会尽力使其完全正确。

关于ruby-on-rails - RSpec, stub 嵌套资源方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2554195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com