我的控制器规格文件中有这个
it "should raise 404" do
business = FactoryGirl.build(:business)
expect{get :edit, :id => business}.to raise_error(ActiveRecord::RecordNotFound)
end
如果我是对的,构建不会保存到数据库,因此业务不应该存在,我的测试应该通过,但事实并非如此。
我还尝试将字符串作为“id”的值,但它仍然失败。
我尝试过这个控制器动作:
def edit
if params[:id].to_i == 0
name = params[:id].to_s.titleize
@business = Business.find_by_name!(name)
else
@business = Business.find(params[:id])
end
respond_with(@business)
end
不存在的ID,确实显示404.
如果你问为什么这样的条件,我也会让这个动作响应“id”参数的字符串。
应用程序控制器中的此代码接收到任何ActiveRecord :: RecordNotFound:
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
private
def record_not_found
render :text => "404 Not Found Baby!", :status => 404
end
为什么我对404的测试没有通过?
答案 0 :(得分:4)
您的控制器不会引发ActiveRecord::RecordNotFound
异常,它会在ApplicationController中从中获取。因此,请尝试测试响应代码或文本,例如
it "should respond with a 404" do
business = FactoryGirl.build(:business)
get :edit, :id => business
response.response_code.should == 404
end
答案 1 :(得分:2)
我知道我迟到了,但你不应该真的在控制器测试中创建记录。您可以在模型测试中创建记录。
在您的控制器测试中,如果您希望创建失败,请使用my_model.stub(:save).and_return(false)
之类的内容将其存根。如果您希望创建成功,可以使用my_model.stub(:save).and_return(true)
使用Shoulda ....
context "record valid" do
before :each do
my_model.stub(:save).and_return(true)
post :create
end
it { should redirect_to(dashboard_url) }
end