gpt4 book ai didi

ruby-on-rails - Rspec:如何 stub 私有(private)方法?

转载 作者:行者123 更新时间:2023-12-04 18:50:51 24 4
gpt4 key购买 nike

这是错误:

private method `desc' called for #<Array:0x0000010532e280>

规范:
describe SubjectsController do  
before(:each) do
@subject = mock_model(Subject)
end

describe "#0002 - GET #index" do
before(:each) do
subjects = [@subject, mock_model(Subject), mock_model(Subject)]
Subject.stub!(:all).and_return(subjects)
Subject.all.stub!(:desc).and_return(subjects)
get :index
end

it { response.should be_success }
it { response.should render_template("index") }
end
end

和 Controller :
def index
@subjects = Subject.all(conditions: {company_id: current_user.company.id}).desc(:created_at)
end

我不知道如何解决这个问题,有人可以帮我吗?
您能否就如何测试这种方法给我建议?
谢谢。

最佳答案

这比我更喜欢的 mock 和链接,但是,你可以这样做:

subjects = [...]
desc_mock = double("desc order mock")
desc_mock.should_receive(:desc).with(:created_at).and_return(subjects)

conditions = {...}
Subject.should_receive(:all).with(conditions).and_return(desc_mock)

您还可以通过将查询移动到带有一些参数的命名范围中来大大简化这一点。然后,您的测试可以验证 Subject 收到了您的范围,其中包含正确的参数,例如:
Subject.should_receive(:user_company).with(current_user.id).and_return(subjects)

关于ruby-on-rails - Rspec:如何 stub 私有(private)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6358950/

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