RSPEC Redirect_To语法

时间:2013-06-01 00:46:04

标签: ruby-on-rails rspec

问候所有人 - 我是rspec测试的新手,正在跟随Aaron Sumner的dailyrailsrspec pdf。我在控制器测试中遇到redirect_to问题。我在客户控制器中测试我的创建操作。创建记录后,我会重定向到我的“列表”操作。试图测试这个让我适合。

我的rspec控制器测试:

describe 'POST #create' do
  context "with valid attributes" do
    it "saves the new customer in the database" do
      expect{
        post :create, customer: attributes_for(:customer)
      }
    end

    it "redirects to list page" do
      post :create, customer: attributes_for(:customer)
      expect(response).to redirect_to(:action => list)
    end
  end
end

“它保存......”测试通过,但重定向不通过。在pdf中,它显示了使用'customer_url'的示例。我从http://rspec.rubyforge.org/rspec-rails/1.1.12/classes/Spec/Rails/Matchers.html获得了我使用的语法(上面),但它对我不起作用。

错误输出:

故障:

1) CustomersController while signed in POST #create with valid attributes redirects to list page
 Failure/Error: expect(response).to redirect_to(:action => list)
 NameError:
   undefined local variable or method `customer' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1::Nested_5::Nested_1:0x007fdcbfe88f20>

我已尝试将控制器名称添加到测试中,如&gt;&gt; redirect_to(:controller =&gt; customers,:action =&gt; list),但也失败了。

帮助?感谢。

1 个答案:

答案 0 :(得分:2)

错误是"customer is not defined"。我假设您正在使用FactoryGirl,并且您已定义customer工厂。如果这是正确的,那么您在Factory哈希

中省略了customer方法
it "redirects to list page" do
  post :create, customer: Factory.attributes_for(:customer)
  expect(response).to redirect_to(:action => list)
end

您也可以像这样写

it "redirects to list page" do
  post :create, customer: Factory.attributes_for(:customer)
  response.should redirect_to(:action => list)
end

此外,在第一次测试时,我建议添加

it "saves the new customer in the database" do
  expect{
    post :create, customer: Factory.attributes_for(:customer)
  }.to change(Customer,:count).by(1)
end

这可以让你走上正轨