【发布时间】:2019-03-19 05:50:54
【问题描述】:
我正在尝试为控制器的 show 方法编写测试。
方法如下:
def show
if current_user
goal= Goal.find_by_name(params[:id], :include => :projects, :conditions => ['projects.flag = true OR projects.user_id = ?', current_user.id])
else
goal= Goal.find_by_name(params[:id], :include => :projects, :conditions => ['projects.flag = true'])
end
@results = goal.projects if goal
end
这是我目前的测试:
describe '#show' do
before :each do
@user = FactoryGirl.create(:user)
@project= FactoryGirl.create(:project, user: @user, flag: 1)
@goal= FactoryGirl.create(:goal, name: 'goal')
@goal_association= FactoryGirl.create(:goal_association, goal_id: @goal.id, project_id: @project.id)
controller.stub(:current_user).and_return(@user)
end
it 'search by goal' do
get :show, id: @goal.name
expect(response.status).to eq 302
end
end
此测试返回以下错误:
Failure/Error: get :show, id: @goal.name
ArgumentError:
wrong number of arguments (2 for 1)
错误指向goal= Goal.find_by_name(params[:id], :include => :projects, :conditions => ['projects.flag = true OR projects.user_id = ?', current_user.id]) 行。
我不知道该怎么做。 任何有关这方面的线索都会有所帮助。
【问题讨论】:
-
您使用的是什么 Rails 版本?您的
find_by_name使用尝试建议 2.x。 -
我正在使用 rails 版本 4.1.16 @MarekLipka 我不知道如何为这个方法编写测试。你能帮帮我吗?
-
好吧,看看我的回答,应该可以的。而且我想您应该注意,您从 StackOverflow 复制的代码有多旧,因为很多答案都已过时。 :)
-
它似乎无法识别
scope。我可以改用Goal.find_by(name: params[:id])对吗? @MarekLipka -
我包括设置
scope。但是,是的,你可以。
标签: ruby-on-rails rspec controller rspec-rails