2

大家好——我是 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>

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

帮助?谢谢。

4

1 回答 1

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

这应该让你走上正轨

于 2013-06-01T04:56:16.230 回答